前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Python爬虫】15行代码教你爬B站视频弹幕,词云图展示数据(附源码)

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

作者头像
松鼠爱吃饼干
发布2021-10-14 16:50:56
1.2K0
发布2021-10-14 16:50:56
举报
文章被收录于专栏:Python分享Python分享Python分享

知识点

  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

有疑问的同学,或者想要Python相关资料的可以加群:1039649593 找管理员领取资料和一对一解答

爬虫代码

导入模块

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)

词云代码

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')
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2021-10-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 松鼠爱吃饼干 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 知识点
  • 开发环境
  • 代码实现过程步骤:
  • 有疑问的同学,或者想要Python相关资料的可以加群:1039649593 找管理员领取资料和一对一解答
  • 爬虫代码
    • 导入模块
      • 发送请求
        • 解析数据
          • 保存数据
          • 词云代码
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档