【Python学习】网络爬虫-获取B站弹幕时间并制作折线图
import requests
from datetime import datetime
import matplotlib.pyplot as plt
# 获取B站弹幕服务器时间
def get_bilibili_popularity_times():
url = 'https://api.live.bilibili.com/ajax/room/popularity'
params = {
'room_id': 21464441, # 替换为你想监控的直播间房间号
}
response = requests.get(url, params=params)
if response.status_code == 200:
times = [item['time'] for item in response.json()['data']['list']]
return [datetime.fromtimestamp(int(time)) for time in times]
else:
return []
# 绘制弹幕时间折线图
def draw_popularity_times_chart(times):
if times:
times_x_axis = range(len(times))
plt.figure(figsize=(10, 5))
plt.plot(times_x_axis, times, 'b-')
plt.title('B站弹幕时间')
plt.xlabel('时间序列')
plt.ylabel('弹幕时间')
plt.xticks(rotation=45)
plt.show()
# 主程序入口
if __name__ == '__main__':
times = get_bilibili_popularity_times()
draw_popularity_times_chart(times)
这段代码首先定义了一个获取B站弹幕时间的函数get_bilibili_popularity_times
,它使用requests库向B站弹幕API发送请求,并解析返回的JSON数据以提取时间戳。然后定义了绘制时间折线图的函数draw_popularity_times_chart
,它使用matplotlib.pyplot绘制时间序列图。最后,在主程序中调用这两个函数,获取并展示了B站直播间弹幕的时间序列。
评论已关闭