download_v3.py 8.9 KB

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