栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【Python爬虫】15行代码教你爬B站视频弹幕,词云图展示数据(附源码)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Python爬虫】15行代码教你爬B站视频弹幕,词云图展示数据(附源码)

知识点
  1. 爬虫基本流程
  2. 正则
  3. requests >>> pip install requests
  4. jieba >>> pip install jieba
  5. imageio >>> pip install imageio
  6. wordcloud >>> pip install wordcloud
开发环境
  • add path 勾选 其他可以默认安装
  • Python越新的版本 代表的一些模块不太兼容
  • Python 3.6 / 3.8 >>> python解释器(环境)
  • Pycharm >>> python编辑器

【付费VIP完整版】只要看了就能学会的教程,80集Python基础入门视频教学

点这里即可免费在线观看 代码实现过程步骤:
  1. 导入模块
  2. 发送请求 对于 弹幕url发送请求
  3. 解析数据 提取我们想要弹幕内容
  4. 保存数据 爬取弹幕 可以保存csv文件 保存txt
爬虫代码 导入模块
import requests
import re
发送请求
url = 'https://api.bilibili.com/x/v1/dm/list.so?oid=392402545'
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36'
}
response = requests.get(url=url, headers=headers)
response.encoding = response.apparent_encoding
解析数据
# re 正则表达式
html_data = re.findall('(.*?)', response.text)
print(html_data)
保存数据
for index in html_data:
    with open('弹幕1.txt', mode='a', encoding='utf-8')  as f:
        f.write(index)
        f.write('n')
        print(index)

词云代码
import jieba # 分词模块 pip install jiebe
import wordcloud # 词云模块 pip install wordcloud
import imageio # 自定义词云样式 pip install imageio

py = imageio.imread('python.png')
# 词云 统计哪些词语出现次数比较多, 次数出现的越多的话 字体显示越大
f = open('弹幕1.txt', encoding='utf-8')
txt = f.read()
# print(txt)
txt_list = jieba.lcut(txt)
string = ' '.join(txt_list)
print(string)

wc = wordcloud.WordCloud(
    width=500, # 宽度
    height=500, # 高度
    background_color='white', # 背景颜色
    font_path='msyh.ttc', # 字体文件
    mask=py,
    stopwords={'了', '这个', '啊', '我', '的'}, # 停用词
    # contour_width=5,
    # contour_color='red'

)
wc.generate(string)
wc.to_file('output3.png')

对于本篇文章有疑问,或者想要数据集的同学也可以点这里
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/300004.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号