附加题2代码

main
pw4izm9rs 2 months ago
parent 0a519c8a6e
commit f3ef196c04

@ -0,0 +1,56 @@
import requests
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt
url = "https://api.bilibili.com/x/v1/dm/list.so?oid=1643253304"
# 伪装成浏览器访问
header = {"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0"}
response = requests.get(url, headers=header)
response.encoding = 'utf-8'
xml = response.text
soup = BeautifulSoup(xml, "lxml")
content_all = soup.find_all(name="d")
timeList = []
# for循环遍历content_all
for content in content_all:
# 使用.attrs获取p对应的属性值并赋值给data
data = content.attrs["p"]
# 使用split()函数分割data把第一个元素时间赋值给time
time = data.split(",")[0]
# 将time转换成浮点数添加进列表timeList中
timeList.append(float(time))
danmu_dict = {}
for i in range(7):
start = 30 * i + 1
end = 30 * (i + 1)
x = f"{start}-{end}"
danmu_dict[x] = 0
for danmu in danmu_dict.keys():
# 使用split()分隔字典的键获取第一项赋值给变量start
start = danmu.split("-")[0]
# 使用split()分隔字典的键获取第二项赋值给变量end
end = danmu.split("-")[1]
for time in timeList:
if int(start) <= time <= int(end):
danmu_dict[danmu] = danmu_dict[danmu] + 1
path = 'D:/雷电大魔王/Python/软工作业/软工作业/' # 保存路径
name = 'danmu' # 图表名称
plt.title(name+"_chart")
plt.rc('font',family='SimHei'); plt.rc('font',size=17)
#提取字典的键和值
x = list(danmu_dict .keys())
y = list(danmu_dict.values())
#绘制折线图
plt.plot(x, y)
plt.xlabel('X')
plt.ylabel('Y')
plt.savefig(path + "/" + r"弹幕统计图.png")
Loading…
Cancel
Save