【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编辑器

代码实现过程步骤:

  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('<d p=".*?">(.*?)</d>', 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)

 

 

 

对于本篇文章有疑问的同学可以加【资料白嫖、解答交流群:1039649593】

词云代码

复制代码
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')
复制代码

 

 

 

 

 

posted @   松鼠爱吃饼干  阅读(667)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
Title
点击右上角即可分享
微信分享提示