bilibili_video_download_v1.py 8.3 KB

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