返回列表 发布新帖

[Win软件] 下载 bilibili 字幕的脚本, 分享一下

65 1
发表于 2024-4-19 09:14:10 | 查看全部 阅读模式 来自: 江苏南通

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
本帖最后由 牙签执法官 于 2024-4-19 09:17 编辑

想下载一个视频教程,发现字幕没有下载. 网上也没有工具,代码如下:
  1. """下载哔哩哔哩 字幕
  2. """
  3. import math
  4. import os
  5. import time

  6. import requests
  7. import json


  8. def convert_json_to_srt(json_files_path):
  9.     """
  10.     json 格式的字幕转为 srt 格式
  11.     代码来源 https://www.jianshu.com/p/66450e9554f8
  12.     """
  13.     json_files = os.listdir(json_files_path)
  14.     srt_files_path = os.path.join(json_files_path, 'srt')  # 更改后缀后字幕文件的路径
  15.     isExists = os.path.exists(srt_files_path)
  16.     if not isExists:
  17.         os.mkdir(srt_files_path)

  18.     for json_file in json_files:
  19.         file_name = json_file.replace(json_file[-5:], '.srt')  # 改变转换后字幕的后缀
  20.         file = ''  # 这个变量用来保存数据
  21.         i = 1
  22.         # 将此处文件位置进行修改,加上utf-8是为了避免处理中文时报错
  23.         with open(os.path.join(json_files_path, json_file), encoding='utf-8') as f:
  24.             datas = json.load(f)  # 加载文件数据
  25.             f.close()

  26.         for data in datas['body']:
  27.             start = data['from']  # 获取开始时间
  28.             stop = data['to']  # 获取结束时间
  29.             content = data['content']  # 获取字幕内容
  30.             file += '{}\n'.format(i)  # 加入序号
  31.             hour = math.floor(start) // 3600
  32.             minute = (math.floor(start) - hour * 3600) // 60
  33.             sec = math.floor(start) - hour * 3600 - minute * 60
  34.             minisec = int(math.modf(start)[0] * 100)  # 处理开始时间
  35.             file += str(hour).zfill(2) + ':' + str(minute).zfill(2) + ':' + str(sec).zfill(2) + ',' + str(
  36.                 minisec).zfill(2)  # 将数字填充0并按照格式写入
  37.             file += ' --> '
  38.             hour = math.floor(stop) // 3600
  39.             minute = (math.floor(stop) - hour * 3600) // 60
  40.             sec = math.floor(stop) - hour * 3600 - minute * 60
  41.             minisec = abs(int(math.modf(stop)[0] * 100 - 1))  # 此处减1是为了防止两个字幕同时出现
  42.             file += str(hour).zfill(2) + ':' + str(minute).zfill(2) + ':' + str(sec).zfill(2) + ',' + str(
  43.                 minisec).zfill(2)
  44.             file += '\n' + content + '\n\n'  # 加入字幕文字
  45.             i += 1
  46.         with open(os.path.join(srt_files_path, file_name), 'w', encoding='utf-8') as f:
  47.             f.write(file)  # 将数据写入文件


  48. def download_subtitle_json(bvid: str):
  49.     """
  50.     下载字幕
  51.     """
  52.     sub_dir = f'./{bvid}'
  53.     if not os.path.isdir(sub_dir):
  54.         os.mkdir('./{bvid}')
  55.     headers = {
  56.         'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:125.0) Gecko/20100101 Firefox/125.0',
  57.         'Accept': 'application/json, text/plain, */*',
  58.         'Accept-Language': 'en-US,en;q=0.5',
  59.         # 'Accept-Encoding': 'gzip, deflate, br',
  60.         'Referer': 'https://www.bilibili.com/video/{bvid}/?p=1',
  61.         'Origin': 'https://www.bilibili.com',
  62.         'Connection': 'keep-alive',
  63.         # TODO 改为 自己的cookie , 通过浏览器的 network(网络) 复制
  64.         'Cookie': "",
  65.         'Sec-Fetch-Dest': 'empty',
  66.         'Sec-Fetch-Mode': 'cors',
  67.         'Sec-Fetch-Site': 'same-site',
  68.     }
  69.     resp = requests.get(f'https://www.bilibili.com/video/{bvid}/', headers=headers)
  70.     text = resp.text
  71.     aid = text[text.find('"aid"') + 6:]
  72.     aid = aid[:aid.find(',')]
  73.     cid_back = requests.get("http://api.bilibili.com/x/player/pagelist?bvid={}".format(bvid), headers=headers)
  74.     if cid_back.status_code != 200:
  75.         print('获取 playlist 失败')

  76.     cid_json = json.loads(cid_back.content)
  77.     for item in cid_json['data']:
  78.         cid = item['cid']
  79.         title = item['part'] + '.json'

  80.         params = {
  81.             'aid': aid,
  82.             'cid': cid,
  83.             'isGaiaAvoided': 'false',
  84.             'web_location': '1315873',
  85.             'w_rid': '364cdf378b75ef6a0cee77484ce29dbb',
  86.             'wts': int(time.time()),
  87.         }

  88.         wbi_resp = requests.get('https://api.bilibili.com/x/player/wbi/v2', params=params, headers=headers)
  89.         if wbi_resp.status_code != 200:
  90.             print('获取 字幕链接 失败')
  91.         subtitle_links = wbi_resp.json()['data']["subtitle"]['subtitles']
  92.         if subtitle_links:
  93.             # 默认下载第一个字幕
  94.             subtitle_url = "https:" + subtitle_links[0]['subtitle_url']
  95.             subtitle_resp = requests.get(subtitle_url, headers=headers)
  96.             open(os.path.join(sub_dir, title), 'w', encoding='utf-8').write(subtitle_resp.text)


  97. if __name__ == '__main__':
  98.     # todo 改成需要下载的 bvid, https://www.bilibili.com/video/<bvid>
  99.     BVID = 'BV1s8411v7nE'
  100.     download_subtitle_json(BVID)
  101.     # convert_json_to_srt(f'./{BVID}')
复制代码

评论1

牙签执法官楼主Lv.8实名认证 版主 创作者 开发者 赞助者 发表于 2024-4-19 09:17:59 | 查看全部 来自: 江苏南通
[Python] 代码

回复

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

本版积分规则

关闭

站长推荐上一条 /3 下一条

幸运大抽奖,更多好礼等你来抢!
投诉/建议联系

8641340@qq.com

欢迎各位朋友加入本社区,
共同维护良好的社区氛围
  • 加入QQ群
  • 添加微信客服
Copyright © 2001-2024 荷包蛋部落 版权所有 All Rights Reserved. 鲁ICP备20023396号-6
关灯 在本版发帖
扫一扫添加微信客服
QQ客服返回顶部
快速回复 返回顶部 返回列表