python爬取b站视频信息
时间: 2025-05-09 15:38:51 浏览: 17
### 使用 Python 实现 B 站视频详情数据抓取
为了实现这一目标,可以采用 `requests` 和 `BeautifulSoup` 库来处理静态页面中的 HTML 数据;对于动态加载的内容,则可能需要用到像 Selenium 这样的工具模拟浏览器行为获取 JavaScript 渲染后的 DOM 结构[^1]。
#### 准备工作
安装必要的库:
```bash
pip install requests beautifulsoup4 selenium pandas
```
#### 获取视频详情页 URL 及其 ID
通常情况下,每条视频都有唯一的 AV/BV 编号作为标识符。可以通过正则表达式从给定链接中提取这些编号用于后续 API 请求构建[^2]。
#### 发送 HTTP GET 请求并解析响应体
利用 `requests.get()` 方法向服务器发起请求,并通过 BeautifulSoup 解析返回的文档对象模型 (DOM),定位到 `<script>` 标签内的 JSON 字符串部分,其中包含了视频的具体信息如标题、封面图地址等。
#### 处理 AJAX 加载的数据
如果遇到异步加载的情况,比如评论区或者弹幕列表,就需要进一步研究官方提供的 RESTful 接口文档,直接调用相应的端点以获得更完整的资源描述[^3]。
下面是一个简单的例子展示如何读取和打印某个特定 BV 号对应的视频基本信息:
```python
import re
import json
from bs4 import BeautifulSoup as BS
import requests
def get_video_info(bvid):
url = f"https://www.bilibili.com/video/{bvid}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
'Referer': url,
}
response = requests.get(url=url, headers=headers)
soup = BS(response.text, "html.parser")
script_tags = str(soup.find_all('script'))
pattern = r'window.__INITIAL_STATE__=(.*?);\(function\(\)'
match_result = re.findall(pattern, script_tags)
if not match_result:
raise ValueError("Failed to find video info.")
data_str = match_result[0].strip()
try:
parsed_json = json.loads(data_str)['videoData']
title = parsed_json['title'].replace("\n", "")
desc = parsed_json['desc']
print(f"Title: {title}")
print(f"Description:\n{desc}")
except KeyError as e:
print(e)
if __name__ == "__main__":
bvid_example = input("Enter the target video's BV number:")
get_video_info(bvid=bvid_example)
```
此脚本会访问指定的 B 站视频页面并通过查找包含初始状态的对象字面量来抽取所需的元数据字段。
阅读全文
相关推荐















