一元网络论坛

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 92|回复: 0

B站字幕爬取 Python简易教程

[复制链接]

1万

主题

1万

帖子

5万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
56883
发表于 2024-8-21 15:08:13 | 显示全部楼层 |阅读模式
## 用 Python 抓取 B 站视频字幕
最近看到不少朋友问如何用 Python 获取 B 站视频字幕,这里分享一个简单的代码示例。
```python
import time
import requests
import json
import re
headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0",
    "cookie":"SESSDATA=填入自己cookie中的SESSDATA"
    }
def get_aid_cid(url):  # 获取视频的 aid 和 cid
    response = requests.get(url, headers=headers)
    html_content = response.text
    res_data = re.search(r"window.__INITIAL_STATE__=(.*?);\(function", html_content).group(1)
    cid = json.loads(res_data)["videoData"]["cid"]
    aid = json.loads(res_data)["videoData"]["aid"]
    return aid, cid
def get_subtitle_url(aid, cid):  # 获取字幕网页地址
    url = f"https://api.bilibili.com/x/player/wbi/v2?aid={aid}&cid={cid}"
    resp = requests.get(url, headers=headers)
    subtitle_url = resp.json()['data']['subtitle']['subtitles'][0]['subtitle_url']
    return "https:" + subtitle_url
def handle_subtitle(subtitle_url):  # 处理字幕文字
    response = requests.get(subtitle_url, headers=headers)
    subtitle_ls = response.json()['body']
    for i in subtitle_ls[:10]: # 遍历前 10 条字幕文字
        time_from = i['from']
        time_to = i['to']
        print(f"{time_from} -> {time_to}\n{i['content']}")
if __name__ == "__main__":
    url = "https://www.bilibili.com/video/BV1e1YyeoEt6/" # B 站视频地址
    aid,cid = get_aid_cid(url)
    time.sleep(1)
    subtitle_url = get_subtitle_url(aid,cid)
    time.sleep(1)
    handle_subtitle(subtitle_url)
```
代码示例展示了如何获取 B 站视频的字幕,并简单地打印了前 10 条字幕。你可以根据自己的需要调整代码,例如获取全部字幕、保存字幕到文件等等。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|一元网络论坛

GMT+8, 2024-9-20 22:58 , Processed in 0.238177 second(s), 20 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表