爬取B站弹幕做折线图
由于网站更新较快,仅供参考学习
pip install +“库名” (安装库)
# 1. 分析网页,找到弹幕所在网页位置;
# 2. 向网页发送请求,获取网页代码;
# 3. 解析网页,提取弹幕发布时间;
# 4. 将弹幕发布时间进行分段统计;
# 5. 绘制折线图。
import requests
from bs4 import BeautifulSoup
from pyecharts.charts import Line # 想要生成折线图
cid = "381898365"
url = f"https://comment.bilibili.com/{cid}.xml"
response = requests.get(url)
# print(response.encoding) # 获取编码方式
# print(response.apparent_encoding) # .apparent_encoding 属性会从网页的内容中分析网页编码的方式。基于解析的编码不一定正确,作为备选方案
response.encoding = "utf-8"
xml = response.text
soup = BeautifulSoup(xml, "lxml")
content_all = soup.find_all(name="d")
timeList = []
# .content 属性的作用获取二进制数据;.text 属性的作用是获取网页内容;
# .encoding 属性的作用是找出 requests 模块使用了什么编码方式
for comment in content_all:
data = comment.attrs["p"] # 使用.attrs获取p对应的属性值,并赋值给data
# print(data)
datalist = data.split(",") # 遇到“,”就分开
time = data.split(",")[0] # 第一个元素
# print(datalist)
timeList.append(float(time)) # 将time转换成浮点数,添加进列表timeList中
# print(timeList)
subtitlesDict = {}
for x in range(25):
start = 30*x+1
end = 30*(x+1)
segment_range = f"{start}-{end}"
subtitlesDict[segment_range] = 0 # 把 segment_range 作为字典 subtitlesDict 的键,添加进字典中,再将字典中键所对应的值设置为 0
for subtitle in subtitlesDict.keys():
start_key = subtitle.split("-")[0]
end_key = subtitle.split("-")[1] # 使用split()分隔字典的键获取第二项,赋值给变量end_key
# 获取第一项也就分段区间的开始时间,赋值给变量
# start_key;获取第二项也就分段区间的结束时间,赋值给变量end_key
for item in timeList:
if int(float(start_key)) <= item <= int(float(end_key)): # 如果弹幕分布时间在整型start_key和整型end_key之间
subtitlesDict[subtitle] = subtitlesDict[subtitle] + 1
# add_xaxis() 函数可以设置折线图的 x 轴。
line = Line()
line.add_xaxis(list(subtitlesDict.keys())) # 使用list()将字典subtitlesDict所有键转换成列表,传入add_xaxis()中
line.add_yaxis("弹幕数", list(subtitlesDict.values())) # 将字典subtitlesDict所有值转换成列表,作为参数添加进函数中
line.render("line.html") # 使用render()函数存储文件,设置文件名为line.html
print("success!!!!!!!!")
运行成功同级目录下有html文件,用网页打开就可以看见折线图啦