<<返回python首页 python

《Python 应用案例》

Python爬取可视化《后浪》的弹幕

img

前几天 B 站上线了一个小视频《后浪》,在全网引起了热烈反响,有赞扬也有批评,视频地址:https://www.bilibili.com/video/BV1FV411d7u7,本文我们爬一下视频弹幕来了解一下 B 站网友对视频的看法。

如何获取弹幕文件地址

视频弹幕是存在 xml 文件中的,链接的格式为:http://comment.bilibili.com/cid.xml,我们只需要拿到视频弹幕的 cid 即可,看一下获取方式,我们先打开视频链接 https://www.bilibili.com/video/BV1FV411d7u7,接着按 F12 键打开开发者工具选择 Network,再刷新一下网页,我们到过滤框中输入 view?type ,就可以看到cid的值了

image-20200805084456044

image-20200805084504171

弹幕爬取Python实现:

安装相关库

!pip3 install jieba -i https://pypi.tuna.tsinghua.edu.cn/simple
!pip3 install wordcloud -i https://pypi.tuna.tsinghua.edu.cn/simple
!pip3 install beautifulsoup4 -i https://pypi.tuna.tsinghua.edu.cn/simple
!pip3 install pillow -i https://pypi.tuna.tsinghua.edu.cn/simple
!pip3 install lxml -i https://pypi.tuna.tsinghua.edu.cn/simple

导入库

import requests
import pandas as pd
import numpy as np
from bs4 import BeautifulSoup
import jieba
from wordcloud import WordCloud
from PIL import Image

抓取弹幕文件并保存

url = "http://comment.bilibili.com/186803402.xml"
req = requests.get(url)
html = req.content
html_doc = str(html, "utf-8")  # 修改成utf-8
# 解析
soup = BeautifulSoup(html_doc, "lxml")
results = soup.find_all('d')
contents = [x.text for x in results]
# 保存结果
dic = {"contents": contents}
df = pd.DataFrame(dic)
df["contents"].to_csv("bili.csv", encoding="utf-8", index=False)
df

定义处理函数

def jieba_():
    # 打开评论数据文件
    content = open("bili.csv", "rb").read()
    # jieba 分词
    word_list = jieba.cut(content)
    words = []
    # 过滤掉的词
    stopwords = open("/share/txt/stopwords.txt", "r", encoding="utf-8").read().split("\n")[:-1]

    for word in word_list:
        if word not in stopwords:
            words.append(word)
    global word_cloud
    # 用逗号隔开词语
    word_cloud = ','.join(words)

def cloud():
    # 打开词云背景图
    cloud_mask = np.array(Image.open("/share/image/houlang.jpg"))
    # 定义词云的一些属性
    wc = WordCloud(
        # 背景图分割颜色为白色
        background_color='white',
        # 背景图样
        mask=cloud_mask,
        # 显示最大词数
        max_words=500,
        # 显示中文
        font_path='./share/fonts/simhei.ttf',
        # 最大尺寸
        max_font_size=60,
        repeat=True
    )
    global word_cloud
    # 词云函数
    x = wc.generate(word_cloud)
    # 生成词云图片
    image = x.to_image()
    # 展示词云图片
    image.show()
    # 保存词云图片
    wc.to_file('cloud.png')

jieba_()
cloud()

查看词云图片

from IPython.display import Image as ImageOpen
ImageOpen(filename = "/root/cloud.png")

总结

本节通过对弹幕文件的获取,解析,去除停用词,词云展示等一系列操作,简便实现了网络评论/弹幕的快速分析。

移动端设备除iPad Pro外,其它移动设备仅能阅读基础的文本文字。
建议使用PC或笔记本电脑,浏览器使用Chrome或FireFox进行浏览,以开启左侧互动实验区来提升学习效率,推荐使用的分辨率为1920x1080或更高。
我们坚信最好的学习是参与其中这一理念,并致力成为中文互联网上体验更好的学练一体的IT技术学习交流平台。
您可加QQ群:575806994,一起学习交流技术,反馈网站使用中遇到问题。
内容、课程、广告等相关合作请扫描右侧二维码添加好友。

狐狸教程 Copyright 2021

进入全屏