bilibili_video_download_v3.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. # !/usr/bin/python
  2. # -*- coding:utf-8 -*-
  3. # time: 2019/07/02--08:12
  4. __author__ = 'Henry'
  5. '''
  6. 项目: B站视频下载 - 多线程下载
  7. 版本1: 加密API版,不需要加入cookie,直接即可下载1080p视频
  8. 20190422 - 增加多P视频单独下载其中一集的功能
  9. 20190702 - 增加视频多线程下载 速度大幅提升
  10. '''
  11. import requests, time, hashlib, urllib.request, re, json
  12. from moviepy.editor import *
  13. import os, sys, threading
  14. import imageio
  15. imageio.plugins.ffmpeg.download()
  16. # 访问API地址
  17. def get_play_list(start_url, cid, quality):
  18. entropy = 'rbMCKn@KuamXWlPMoJGsKcbiJKUfkPF_8dABscJntvqhRSETg'
  19. appkey, sec = ''.join([chr(ord(i) + 2) for i in entropy[::-1]]).split(':')
  20. params = 'appkey=%s&cid=%s&otype=json&qn=%s&quality=%s&type=' % (appkey, cid, quality, quality)
  21. chksum = hashlib.md5(bytes(params + sec, 'utf8')).hexdigest()
  22. url_api = 'https://interface.bilibili.com/v2/playurl?%s&sign=%s' % (params, chksum)
  23. headers = {
  24. 'Referer': start_url, # 注意加上referer
  25. 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
  26. }
  27. # print(url_api)
  28. html = requests.get(url_api, headers=headers).json()
  29. # print(json.dumps(html))
  30. video_list = [html['durl'][0]['url']]
  31. # print(video_list)
  32. return video_list
  33. # 下载视频
  34. '''
  35. urllib.urlretrieve 的回调函数:
  36. def callbackfunc(blocknum, blocksize, totalsize):
  37. @blocknum: 已经下载的数据块
  38. @blocksize: 数据块的大小
  39. @totalsize: 远程文件的大小
  40. '''
  41. def Schedule_cmd(blocknum, blocksize, totalsize):
  42. speed = (blocknum * blocksize) / (time.time() - start_time)
  43. # speed_str = " Speed: %.2f" % speed
  44. speed_str = " Speed: %s" % format_size(speed)
  45. recv_size = blocknum * blocksize
  46. # 设置下载进度条
  47. f = sys.stdout
  48. pervent = recv_size / totalsize
  49. percent_str = "%.2f%%" % (pervent * 100)
  50. n = round(pervent * 50)
  51. s = ('#' * n).ljust(50, '-')
  52. f.write(percent_str.ljust(8, ' ') + '[' + s + ']' + speed_str)
  53. f.flush()
  54. # time.sleep(0.1)
  55. f.write('\r')
  56. def Schedule(blocknum, blocksize, totalsize):
  57. speed = (blocknum * blocksize) / (time.time() - start_time)
  58. # speed_str = " Speed: %.2f" % speed
  59. speed_str = " Speed: %s" % format_size(speed)
  60. recv_size = blocknum * blocksize
  61. # 设置下载进度条
  62. f = sys.stdout
  63. pervent = recv_size / totalsize
  64. percent_str = "%.2f%%" % (pervent * 100)
  65. n = round(pervent * 50)
  66. s = ('#' * n).ljust(50, '-')
  67. print(percent_str.ljust(6, ' ') + '-' + speed_str)
  68. f.flush()
  69. time.sleep(2)
  70. # print('\r')
  71. # 字节bytes转化K\M\G
  72. def format_size(bytes):
  73. try:
  74. bytes = float(bytes)
  75. kb = bytes / 1024
  76. except:
  77. print("传入的字节格式不对")
  78. return "Error"
  79. if kb >= 1024:
  80. M = kb / 1024
  81. if M >= 1024:
  82. G = M / 1024
  83. return "%.3fG" % (G)
  84. else:
  85. return "%.3fM" % (M)
  86. else:
  87. return "%.3fK" % (kb)
  88. # 下载视频
  89. def down_video(video_list, title, start_url, page):
  90. num = 1
  91. print('[正在下载P{}段视频,请稍等...]:'.format(page) + title)
  92. currentVideoPath = os.path.join(sys.path[0], 'bilibili_video', title) # 当前目录作为下载目录
  93. for i in video_list:
  94. opener = urllib.request.build_opener()
  95. # 请求头
  96. opener.addheaders = [
  97. # ('Host', 'upos-hz-mirrorks3.acgvideo.com'), #注意修改host,不用也行
  98. ('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:56.0) Gecko/20100101 Firefox/56.0'),
  99. ('Accept', '*/*'),
  100. ('Accept-Language', 'en-US,en;q=0.5'),
  101. ('Accept-Encoding', 'gzip, deflate, br'),
  102. ('Range', 'bytes=0-'), # Range 的值要为 bytes=0- 才能下载完整视频
  103. ('Referer', start_url), # 注意修改referer,必须要加的!
  104. ('Origin', 'https://www.bilibili.com'),
  105. ('Connection', 'keep-alive'),
  106. ]
  107. urllib.request.install_opener(opener)
  108. # 创建文件夹存放下载的视频
  109. if not os.path.exists(currentVideoPath):
  110. os.makedirs(currentVideoPath)
  111. # 开始下载
  112. if len(video_list) > 1:
  113. urllib.request.urlretrieve(url=i, filename=os.path.join(currentVideoPath, r'{}-{}.flv'.format(title, num)),reporthook=Schedule_cmd) # 写成mp4也行 title + '-' + num + '.flv'
  114. else:
  115. urllib.request.urlretrieve(url=i, filename=os.path.join(currentVideoPath, r'{}.flv'.format(title)),reporthook=Schedule_cmd) # 写成mp4也行 title + '-' + num + '.flv'
  116. num += 1
  117. # 合并视频
  118. def combine_video(video_list, title):
  119. currentVideoPath = os.path.join(sys.path[0], 'bilibili_video', title) # 当前目录作为下载目录
  120. if len(video_list) >= 2:
  121. # 视频大于一段才要合并
  122. print('[下载完成,正在合并视频...]:' + title)
  123. # 定义一个数组
  124. L = []
  125. # 访问 video 文件夹 (假设视频都放在这里面)
  126. root_dir = currentVideoPath
  127. # 遍历所有文件
  128. for file in sorted(os.listdir(root_dir), key=lambda x: int(x[x.rindex("-") + 1:x.rindex(".")])):
  129. # 如果后缀名为 .mp4/.flv
  130. if os.path.splitext(file)[1] == '.flv':
  131. # 拼接成完整路径
  132. filePath = os.path.join(root_dir, file)
  133. # 载入视频
  134. video = VideoFileClip(filePath)
  135. # 添加到数组
  136. L.append(video)
  137. # 拼接视频
  138. final_clip = concatenate_videoclips(L)
  139. # 生成目标视频文件
  140. final_clip.to_videofile(os.path.join(root_dir, r'{}.mp4'.format(title)), fps=24, remove_temp=False)
  141. print('[视频合并完成]' + title)
  142. else:
  143. # 视频只有一段则直接打印下载完成
  144. print('[视频合并完成]:' + title)
  145. if __name__ == '__main__':
  146. start_time = time.time()
  147. # 用户输入av号或者视频链接地址
  148. print('*' * 30 + 'B站视频下载小助手' + '*' * 30)
  149. start = input('请输入您要下载的B站av号或者视频链接地址:')
  150. if start.isdigit() == True: # 如果输入的是av号
  151. # 获取cid的api, 传入aid即可
  152. start_url = 'https://api.bilibili.com/x/web-interface/view?aid=' + start
  153. else:
  154. # https://www.bilibili.com/video/av46958874/?spm_id_from=333.334.b_63686965665f7265636f6d6d656e64.16
  155. start_url = 'https://api.bilibili.com/x/web-interface/view?aid=' + re.search(r'/av(\d+)/*', start).group(1)
  156. # 视频质量
  157. # <accept_format><![CDATA[flv,flv720,flv480,flv360]]></accept_format>
  158. # <accept_description><![CDATA[高清 1080P,高清 720P,清晰 480P,流畅 360P]]></accept_description>
  159. # <accept_quality><![CDATA[80,64,32,16]]></accept_quality>
  160. quality = input('请输入您要下载视频的清晰度(1080p:80;720p:64;480p:32;360p:16)(填写80或64或32或16):')
  161. # 获取视频的cid,title
  162. headers = {
  163. 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
  164. }
  165. html = requests.get(start_url, headers=headers).json()
  166. data = html['data']
  167. cid_list = []
  168. if '?p=' in start:
  169. # 单独下载分P视频中的一集
  170. p = re.search(r'\?p=(\d+)',start).group(1)
  171. cid_list.append(data['pages'][int(p) - 1])
  172. else:
  173. # 如果p不存在就是全集下载
  174. cid_list = data['pages']
  175. # print(cid_list)
  176. # 创建线程池
  177. threadpool = []
  178. for item in cid_list:
  179. cid = str(item['cid'])
  180. title = item['part']
  181. title = re.sub(r'[\/\\:*?"<>|]', '', title) # 替换为空的
  182. print('[下载视频的cid]:' + cid)
  183. print('[下载视频的标题]:' + title)
  184. page = str(item['page'])
  185. start_url = start_url + "/?p=" + page
  186. video_list = get_play_list(start_url, cid, quality)
  187. start_time = time.time()
  188. # down_video(video_list, title, start_url, page)
  189. # 定义线程
  190. th = threading.Thread(target=down_video, args=(video_list, title, start_url, page))
  191. # 将线程加入线程池
  192. threadpool.append(th)
  193. combine_video(video_list, title)
  194. # 开始线程
  195. for th in threadpool:
  196. th.start()
  197. # 等待所有线程运行完毕
  198. for th in threadpool:
  199. th.join()
  200. end_time = time.time() # 结束时间
  201. print('下载总耗时%.2f秒,约%.2f分钟' % (end_time - start_time, int(end_time - start_time) / 60))
  202. # 如果是windows系统,下载完成后打开下载目录
  203. currentVideoPath = os.path.join(sys.path[0], 'bilibili_video') # 当前目录作为下载目录
  204. if (sys.platform.startswith('win')):
  205. os.startfile(currentVideoPath)
  206. # 分P视频下载测试: https://www.bilibili.com/video/av19516333/
  207. # 下载总耗时14.21秒,约0.23分钟