123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235 |
- __author__ = 'Henry'
- '''
- 项目: B站视频下载 - 多线程下载
- 版本1: 加密API版,不需要加入cookie,直接即可下载1080p视频
- 20190422 - 增加多P视频单独下载其中一集的功能
- 20190702 - 增加视频多线程下载 速度大幅提升
- '''
- import requests, time, hashlib, urllib.request, re, json
- from moviepy.editor import *
- import os, sys, threading
- import imageio
- imageio.plugins.ffmpeg.download()
- def get_play_list(start_url, cid, quality):
- entropy = 'rbMCKn@KuamXWlPMoJGsKcbiJKUfkPF_8dABscJntvqhRSETg'
- appkey, sec = ''.join([chr(ord(i) + 2) for i in entropy[::-1]]).split(':')
- params = 'appkey=%s&cid=%s&otype=json&qn=%s&quality=%s&type=' % (appkey, cid, quality, quality)
- chksum = hashlib.md5(bytes(params + sec, 'utf8')).hexdigest()
- url_api = 'https://interface.bilibili.com/v2/playurl?%s&sign=%s' % (params, chksum)
- headers = {
- 'Referer': start_url,
- 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
- }
-
- html = requests.get(url_api, headers=headers).json()
-
- video_list = [html['durl'][0]['url']]
-
- return video_list
- '''
- urllib.urlretrieve 的回调函数:
- def callbackfunc(blocknum, blocksize, totalsize):
- @blocknum: 已经下载的数据块
- @blocksize: 数据块的大小
- @totalsize: 远程文件的大小
- '''
- def Schedule_cmd(blocknum, blocksize, totalsize):
- speed = (blocknum * blocksize) / (time.time() - start_time)
-
- speed_str = " Speed: %s" % format_size(speed)
- recv_size = blocknum * blocksize
-
- f = sys.stdout
- pervent = recv_size / totalsize
- percent_str = "%.2f%%" % (pervent * 100)
- n = round(pervent * 50)
- s = ('#' * n).ljust(50, '-')
- f.write(percent_str.ljust(8, ' ') + '[' + s + ']' + speed_str)
- f.flush()
-
- f.write('\r')
- def Schedule(blocknum, blocksize, totalsize):
- speed = (blocknum * blocksize) / (time.time() - start_time)
-
- speed_str = " Speed: %s" % format_size(speed)
- recv_size = blocknum * blocksize
-
- f = sys.stdout
- pervent = recv_size / totalsize
- percent_str = "%.2f%%" % (pervent * 100)
- n = round(pervent * 50)
- s = ('#' * n).ljust(50, '-')
- print(percent_str.ljust(6, ' ') + '-' + speed_str)
- f.flush()
- time.sleep(2)
-
- def format_size(bytes):
- try:
- bytes = float(bytes)
- kb = bytes / 1024
- except:
- print("传入的字节格式不对")
- return "Error"
- if kb >= 1024:
- M = kb / 1024
- if M >= 1024:
- G = M / 1024
- return "%.3fG" % (G)
- else:
- return "%.3fM" % (M)
- else:
- return "%.3fK" % (kb)
- def down_video(video_list, title, start_url, page):
- num = 1
- print('[正在下载P{}段视频,请稍等...]:'.format(page) + title)
- currentVideoPath = os.path.join(sys.path[0], 'bilibili_video', title)
- for i in video_list:
- opener = urllib.request.build_opener()
-
- opener.addheaders = [
-
- ('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:56.0) Gecko/20100101 Firefox/56.0'),
- ('Accept', '*/*'),
- ('Accept-Language', 'en-US,en;q=0.5'),
- ('Accept-Encoding', 'gzip, deflate, br'),
- ('Range', 'bytes=0-'),
- ('Referer', start_url),
- ('Origin', 'https://www.bilibili.com'),
- ('Connection', 'keep-alive'),
- ]
- urllib.request.install_opener(opener)
-
- if not os.path.exists(currentVideoPath):
- os.makedirs(currentVideoPath)
-
- if len(video_list) > 1:
- urllib.request.urlretrieve(url=i, filename=os.path.join(currentVideoPath, r'{}-{}.flv'.format(title, num)),reporthook=Schedule_cmd)
- else:
- urllib.request.urlretrieve(url=i, filename=os.path.join(currentVideoPath, r'{}.flv'.format(title)),reporthook=Schedule_cmd)
- num += 1
- def combine_video(video_list, title):
- currentVideoPath = os.path.join(sys.path[0], 'bilibili_video', title)
- if len(video_list) >= 2:
-
- print('[下载完成,正在合并视频...]:' + title)
-
- L = []
-
- root_dir = currentVideoPath
-
- for file in sorted(os.listdir(root_dir), key=lambda x: int(x[x.rindex("-") + 1:x.rindex(".")])):
-
- if os.path.splitext(file)[1] == '.flv':
-
- filePath = os.path.join(root_dir, file)
-
- video = VideoFileClip(filePath)
-
- L.append(video)
-
- final_clip = concatenate_videoclips(L)
-
- final_clip.to_videofile(os.path.join(root_dir, r'{}.mp4'.format(title)), fps=24, remove_temp=False)
- print('[视频合并完成]' + title)
- else:
-
- print('[视频合并完成]:' + title)
- if __name__ == '__main__':
- start_time = time.time()
-
- print('*' * 30 + 'B站视频下载小助手' + '*' * 30)
- start = input('请输入您要下载的B站av号或者视频链接地址:')
- if start.isdigit() == True:
-
- start_url = 'https://api.bilibili.com/x/web-interface/view?aid=' + start
- else:
-
- start_url = 'https://api.bilibili.com/x/web-interface/view?aid=' + re.search(r'/av(\d+)/*', start).group(1)
-
-
-
-
- quality = input('请输入您要下载视频的清晰度(1080p:80;720p:64;480p:32;360p:16)(填写80或64或32或16):')
-
- headers = {
- 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
- }
- html = requests.get(start_url, headers=headers).json()
- data = html['data']
- cid_list = []
- if '?p=' in start:
-
- p = re.search(r'\?p=(\d+)',start).group(1)
- cid_list.append(data['pages'][int(p) - 1])
- else:
-
- cid_list = data['pages']
-
-
- threadpool = []
- for item in cid_list:
- cid = str(item['cid'])
- title = item['part']
- title = re.sub(r'[\/\\:*?"<>|]', '', title)
- print('[下载视频的cid]:' + cid)
- print('[下载视频的标题]:' + title)
- page = str(item['page'])
- start_url = start_url + "/?p=" + page
- video_list = get_play_list(start_url, cid, quality)
- start_time = time.time()
-
-
- th = threading.Thread(target=down_video, args=(video_list, title, start_url, page))
-
- threadpool.append(th)
- combine_video(video_list, title)
-
- for th in threadpool:
- th.start()
-
- for th in threadpool:
- th.join()
- end_time = time.time()
- print('下载总耗时%.2f秒,约%.2f分钟' % (end_time - start_time, int(end_time - start_time) / 60))
-
- currentVideoPath = os.path.join(sys.path[0], 'bilibili_video')
- if (sys.platform.startswith('win')):
- os.startfile(currentVideoPath)
|