python爬取b站视频代码
时间: 2023-10-09 13:05:11 浏览: 119
好的,请稍等,我会为您找到可以爬取B站视频的Python代码。
以下是一段可以爬取B站视频的Python代码:
```
import requests
import json
import os
# 视频av号
av_num = "av170001"
# 获取视频信息
video_info_url = "https://api.bilibili.com/x/web-interface/view?aid=" + av_num
video_info = json.loads(requests.get(url=video_info_url).text)
# 获取视频cid
cid = str(video_info["data"]["cid"])
# 获取视频标题
title = str(video_info["data"]["title"])
# 获取视频每页最大评论数
max_comment = str(video_info["data"]["comment"])
# 获取视频弹幕
danmu_url = "https://api.bilibili.com/x/v1/dm/list.so?oid=" + cid
danmu_xml = requests.get(url=danmu_url).content
open(title + ".xml", "wb").write(danmu_xml)
# 获取视频评论
comment_url = "https://api.bilibili.com/x/v2/reply?type=1&oid=" + cid + "&pn=1&nohot=1&sort=0"
comment_json = json.loads(requests.get(url=comment_url).text)
# 获取所有评论
all_comment = []
for i in range(int(comment_json["data"]["page"]["count"])):
comment_url = "https://api.bilibili.com/x/v2/reply?type=1&oid=" + cid + "&pn=" + str(
i) + "&nohot=1&sort=0"
comment_json = json.loads(requests.get(url=comment_url).text)
for j in range(int(max_comment)):
if j >= len(comment_json["data"]["replies"]):
break
all_comment.append(comment_json["data"]["replies"][j]["content"]["message"])
# 打印所有评论
for comment in all_comment:
print(comment)
print("下载完成!")
```
该代码使用了B站提供的API来获取视频信息、弹幕和评论,具有一定的实用性。如有需要,您可以根据需要进行修改和优化。
阅读全文