目錄
- 項(xiàng)目地址:
- 介紹
- 版本一: bilibili_video_download_v1.py
- 版本二:bilibili_video_download_v2.py
- 版本三: bilibili_video_download_v3.py
- 版本四: GUI版本 - bilibili_video_download-GUI.py
- 版本五: bilibili_video_download_bangumi.py
項(xiàng)目地址:
https://github.com/Henryhaohao/Bilibili_video_download
介紹
- 對(duì)于單P視頻:直接傳入B站av號(hào)或者視頻鏈接地址(eg: 49842011或者h(yuǎn)ttps://www.bilibili.com/video/av49842011)
- 對(duì)于多P視頻:
1.下載全集:直接傳入B站av號(hào)或者視頻鏈接地址(eg: 49842011或者h(yuǎn)ttps://www.bilibili.com/video/av49842011)
2.下載其中一集:傳入那一集的視頻鏈接地址(eg: https://www.bilibili.com/video/av19516333/?p=2)
版本一: bilibili_video_download_v1.py
加密API版,不需要加入cookie,直接即可下載1080p視頻
# !/usr/bin/python
# -*- coding:utf-8 -*-
# time: 2019/04/17--08:12
__author__ = 'Henry'
'''
項(xiàng)目: B站視頻下載
版本1: 加密API版,不需要加入cookie,直接即可下載1080p視頻
20190422 - 增加多P視頻單獨(dú)下載其中一集的功能
'''
import imageio
imageio.plugins.ffmpeg.download()
import requests, time, hashlib, urllib.request, re, json
from moviepy.editor import *
import os, sys
# 訪問(wèn)API地址
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=%scid=%sotype=jsonqn=%squality=%stype=' % (appkey, cid, quality, quality)
chksum = hashlib.md5(bytes(params + sec, 'utf8')).hexdigest()
url_api = 'https://interface.bilibili.com/v2/playurl?%ssign=%s' % (params, chksum)
headers = {
'Referer': start_url, # 注意加上referer
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
}
# print(url_api)
html = requests.get(url_api, headers=headers).json()
# print(json.dumps(html))
video_list = []
for i in html['durl']:
video_list.append(i['url'])
# print(video_list)
return video_list
# 下載視頻
'''
urllib.urlretrieve 的回調(diào)函數(shù):
def callbackfunc(blocknum, blocksize, totalsize):
@blocknum: 已經(jīng)下載的數(shù)據(jù)塊
@blocksize: 數(shù)據(jù)塊的大小
@totalsize: 遠(yuǎn)程文件的大小
'''
def Schedule_cmd(blocknum, blocksize, totalsize):
speed = (blocknum * blocksize) / (time.time() - start_time)
# speed_str = " Speed: %.2f" % speed
speed_str = " Speed: %s" % format_size(speed)
recv_size = blocknum * blocksize
# 設(shè)置下載進(jìn)度條
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()
# time.sleep(0.1)
f.write('\r')
def Schedule(blocknum, blocksize, totalsize):
speed = (blocknum * blocksize) / (time.time() - start_time)
# speed_str = " Speed: %.2f" % speed
speed_str = " Speed: %s" % format_size(speed)
recv_size = blocknum * blocksize
# 設(shè)置下載進(jìn)度條
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)
# print('\r')
# 字節(jié)bytes轉(zhuǎn)化K\M\G
def format_size(bytes):
try:
bytes = float(bytes)
kb = bytes / 1024
except:
print("傳入的字節(jié)格式不對(duì)")
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{}段視頻,請(qǐng)稍等...]:'.format(page) + title)
currentVideoPath = os.path.join(sys.path[0], 'bilibili_video', title) # 當(dāng)前目錄作為下載目錄
for i in video_list:
opener = urllib.request.build_opener()
# 請(qǐng)求頭
opener.addheaders = [
# ('Host', 'upos-hz-mirrorks3.acgvideo.com'), #注意修改host,不用也行
('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-'), # Range 的值要為 bytes=0- 才能下載完整視頻
('Referer', start_url), # 注意修改referer,必須要加的!
('Origin', 'https://www.bilibili.com'),
('Connection', 'keep-alive'),
]
urllib.request.install_opener(opener)
# 創(chuàng)建文件夾存放下載的視頻
if not os.path.exists(currentVideoPath):
os.makedirs(currentVideoPath)
# 開(kāi)始下載
if len(video_list) > 1:
urllib.request.urlretrieve(url=i, filename=os.path.join(currentVideoPath, r'{}-{}.flv'.format(title, num)),reporthook=Schedule_cmd) # 寫成mp4也行 title + '-' + num + '.flv'
else:
urllib.request.urlretrieve(url=i, filename=os.path.join(currentVideoPath, r'{}.flv'.format(title)),reporthook=Schedule_cmd) # 寫成mp4也行 title + '-' + num + '.flv'
num += 1
# 合并視頻
def combine_video(video_list, title):
currentVideoPath = os.path.join(sys.path[0], 'bilibili_video', title) # 當(dāng)前目錄作為下載目錄
if not os.path.exists(currentVideoPath):
os.makedirs(currentVideoPath)
if len(video_list) >= 2:
# 視頻大于一段才要合并
print('[下載完成,正在合并視頻...]:' + title)
# 定義一個(gè)數(shù)組
L = []
# 訪問(wèn) video 文件夾 (假設(shè)視頻都放在這里面)
root_dir = currentVideoPath
# 遍歷所有文件
for file in sorted(os.listdir(root_dir), key=lambda x: int(x[x.rindex("-") + 1:x.rindex(".")])):
# 如果后綴名為 .mp4/.flv
if os.path.splitext(file)[1] == '.flv':
# 拼接成完整路徑
filePath = os.path.join(root_dir, file)
# 載入視頻
video = VideoFileClip(filePath)
# 添加到數(shù)組
L.append(video)
# 拼接視頻
final_clip = concatenate_videoclips(L)
# 生成目標(biāo)視頻文件
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__':
# 用戶輸入av號(hào)或者視頻鏈接地址
print('*' * 30 + 'B站視頻下載小助手' + '*' * 30)
start = input('請(qǐng)輸入您要下載的B站av號(hào)或者視頻鏈接地址:')
if start.isdigit() == True: # 如果輸入的是av號(hào)
# 獲取cid的api, 傳入aid即可
start_url = 'https://api.bilibili.com/x/web-interface/view?aid=' + start
else:
# https://www.bilibili.com/video/av46958874/?spm_id_from=333.334.b_63686965665f7265636f6d6d656e64.16
start_url = 'https://api.bilibili.com/x/web-interface/view?aid=' + re.search(r'/av(\d+)/*', start).group(1)
# 視頻質(zhì)量
# accept_format>![CDATA[flv,flv720,flv480,flv360]]>/accept_format>
# accept_description>![CDATA[高清 1080P,高清 720P,清晰 480P,流暢 360P]]>/accept_description>
# accept_quality>![CDATA[80,64,32,16]]>/accept_quality>
quality = input('請(qǐng)輸入您要下載視頻的清晰度(1080p:80;720p:64;480p:32;360p:16)(填寫80或64或32或16):')
# 獲取視頻的cid,title
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']
video_title=data["title"].replace(" ","_")
cid_list = []
if '?p=' in start:
# 單獨(dú)下載分P視頻中的一集
p = re.search(r'\&;p=(\d+)',start).group(1)
cid_list.append(data['pages'][int(p) - 1])
else:
# 如果p不存在就是全集下載
cid_list = data['pages']
# print(cid_list)
for item in cid_list:
cid = str(item['cid'])
title = item['part']
if not title:
title = video_title
title = re.sub(r'[\/\\:*?">|]', '', title) # 替換為空的
print('[下載視頻的cid]:' + cid)
print('[下載視頻的標(biāo)題]:' + title)
page = str(item['page'])
start_url = start_url + "/?p=" + page
video_list = get_play_list(start_url, cid, quality)
start_time = time.time()
down_video(video_list, title, start_url, page)
combine_video(video_list, title)
# 如果是windows系統(tǒng),下載完成后打開(kāi)下載目錄
currentVideoPath = os.path.join(sys.path[0], 'bilibili_video') # 當(dāng)前目錄作為下載目錄
if (sys.platform.startswith('win')):
os.startfile(currentVideoPath)
# 分P視頻下載測(cè)試: https://www.bilibili.com/video/av19516333/
版本二:bilibili_video_download_v2.py
1.無(wú)加密API版,但是需要加入登錄后cookie中的SESSDATA字段,才可下載720p及以上視頻
2.如果想下載1080p+視頻,需要帶入B站大會(huì)員的cookie中的SESSDATA才行,普通用戶的SESSDATA最多只能下載1080p視頻;請(qǐng)定期更換代碼31行cookie中的SESSDATA值。跟換方法為:瀏覽器登錄B站,在開(kāi)發(fā)者模式(按F12) --> application --> cookie中找到SESSDATA值替換即可,一個(gè)月的有效期
# !/usr/bin/python
# -*- coding:utf-8 -*-
# time: 2019/04/16--17:12
__author__ = 'Henry'
'''
項(xiàng)目: B站視頻下載
版本2: 無(wú)加密API版,但是需要加入登錄后cookie中的SESSDATA字段,才可下載720p及以上視頻
API:
1.獲取cid的api為 https://api.bilibili.com/x/web-interface/view?aid=47476691 aid后面為av號(hào)
2.下載鏈接api為 https://api.bilibili.com/x/player/playurl?avid=44743619cid=78328965qn=32 cid為上面獲取到的 avid為輸入的av號(hào) qn為視頻質(zhì)量
注意:
但是此接口headers需要加上登錄后'Cookie': 'SESSDATA=3c5d20cf%2C1556704080%2C7dcd8c41' (30天的有效期)(因?yàn)楝F(xiàn)在只有登錄后才能看到720P以上視頻了)
不然下載之后都是最低清晰度,哪怕選擇了80也是只有480p的分辨率!!
20190422 - 增加多P視頻單獨(dú)下載其中一集的功能
'''
import requests, time, urllib.request, re
from moviepy.editor import *
import os, sys
import imageio
imageio.plugins.ffmpeg.download()
# 訪問(wèn)API地址
def get_play_list(aid, cid, quality):
url_api = 'https://api.bilibili.com/x/player/playurl?cid={}avid={}qn={}'.format(cid, aid, quality)
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',
'Cookie': 'SESSDATA=aa15d6af%2C1560734457%2Ccc8ca251', # 登錄B站后復(fù)制一下cookie中的SESSDATA字段,有效期1個(gè)月
'Host': 'api.bilibili.com'
}
html = requests.get(url_api, headers=headers).json()
video_list = []
for i in html['data']['durl']:
video_list.append(i['url'])
print(video_list)
return video_list
# 下載視頻
'''
urllib.urlretrieve 的回調(diào)函數(shù):
def callbackfunc(blocknum, blocksize, totalsize):
@blocknum: 已經(jīng)下載的數(shù)據(jù)塊
@blocksize: 數(shù)據(jù)塊的大小
@totalsize: 遠(yuǎn)程文件的大小
'''
def Schedule_cmd(blocknum, blocksize, totalsize):
speed = (blocknum * blocksize) / (time.time() - start_time)
# speed_str = " Speed: %.2f" % speed
speed_str = " Speed: %s" % format_size(speed)
recv_size = blocknum * blocksize
# 設(shè)置下載進(jìn)度條
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()
# time.sleep(0.1)
f.write('\r')
def Schedule(blocknum, blocksize, totalsize):
speed = (blocknum * blocksize) / (time.time() - start_time)
# speed_str = " Speed: %.2f" % speed
speed_str = " Speed: %s" % format_size(speed)
recv_size = blocknum * blocksize
# 設(shè)置下載進(jìn)度條
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)
# print('\r')
# 字節(jié)bytes轉(zhuǎn)化K\M\G
def format_size(bytes):
try:
bytes = float(bytes)
kb = bytes / 1024
except:
print("傳入的字節(jié)格式不對(duì)")
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{}段視頻,請(qǐng)稍等...]:'.format(page) + title)
currentVideoPath = os.path.join(sys.path[0], 'bilibili_video', title) # 當(dāng)前目錄作為下載目錄
for i in video_list:
opener = urllib.request.build_opener()
# 請(qǐng)求頭
opener.addheaders = [
# ('Host', 'upos-hz-mirrorks3.acgvideo.com'), #注意修改host,不用也行
('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-'), # Range 的值要為 bytes=0- 才能下載完整視頻
('Referer', start_url), # 注意修改referer,必須要加的!
('Origin', 'https://www.bilibili.com'),
('Connection', 'keep-alive'),
]
urllib.request.install_opener(opener)
# 創(chuàng)建文件夾存放下載的視頻
if not os.path.exists(currentVideoPath):
os.makedirs(currentVideoPath)
# 開(kāi)始下載
if len(video_list) > 1:
urllib.request.urlretrieve(url=i, filename=os.path.join(currentVideoPath, r'{}-{}.flv'.format(title, num)),
reporthook=Schedule_cmd) # 寫成mp4也行 title + '-' + num + '.flv'
else:
urllib.request.urlretrieve(url=i, filename=os.path.join(currentVideoPath, r'{}.flv'.format(title)),
reporthook=Schedule_cmd) # 寫成mp4也行 title + '-' + num + '.flv'
num += 1
# 合并視頻
def combine_video(video_list, title):
currentVideoPath = os.path.join(sys.path[0], 'bilibili_video', title) # 當(dāng)前目錄作為下載目錄
if len(video_list) >= 2:
# 視頻大于一段才要合并
print('[下載完成,正在合并視頻...]:' + title)
# 定義一個(gè)數(shù)組
L = []
# 訪問(wèn) video 文件夾 (假設(shè)視頻都放在這里面)
root_dir = currentVideoPath
# 遍歷所有文件
for file in sorted(os.listdir(root_dir), key=lambda x: int(x[x.rindex("-") + 1:x.rindex(".")])):
# 如果后綴名為 .mp4/.flv
if os.path.splitext(file)[1] == '.flv':
# 拼接成完整路徑
filePath = os.path.join(root_dir, file)
# 載入視頻
video = VideoFileClip(filePath)
# 添加到數(shù)組
L.append(video)
# 拼接視頻
final_clip = concatenate_videoclips(L)
# 生成目標(biāo)視頻文件
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__':
# 用戶輸入av號(hào)或者視頻鏈接地址
print('*' * 30 + 'B站視頻下載小助手' + '*' * 30)
start = input('請(qǐng)輸入您要下載的B站av號(hào)或者視頻鏈接地址:')
if start.isdigit() == True:
# 如果輸入的是av號(hào)
# 獲取cid的api, 傳入aid即可
aid = start
start_url = 'https://api.bilibili.com/x/web-interface/view?aid=' + aid
else:
# 如果輸入的是url (eg: https://www.bilibili.com/video/av46958874/)
aid = re.search(r'/av(\d+)/*', start).group(1)
start_url = 'https://api.bilibili.com/x/web-interface/view?aid=' + aid
# qn參數(shù)就是視頻清晰度
# 可選值:
# 116: 高清1080P60 (需要帶入大會(huì)員的cookie中的SESSDATA才行,普通用戶的SESSDATA最多只能下載1080p的視頻)
# 112: 高清1080P+ (hdflv2) (需要大會(huì)員)
# 80: 高清1080P (flv)
# 74: 高清720P60 (需要大會(huì)員)
# 64: 高清720P (flv720)
# 32: 清晰480P (flv480)
# 16: 流暢360P (flv360)
print('請(qǐng)輸入您要下載視頻的清晰度(1080p60:116;1080p+:112;1080p:80;720p60:74;720p:64;480p:32;360p:16; **注意:1080p+,1080p60,720p60,720p都需要帶入大會(huì)員的cookie中的SESSDATA才行,普通用戶的SESSDATA最多只能下載1080p的視頻):')
quality = input('請(qǐng)?zhí)顚?16或112或80或74或64或32或16:')
# 獲取視頻的cid,title
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:
# 單獨(dú)下載分P視頻中的一集
p = re.search(r'\&;p=(\d+)', start).group(1)
cid_list.append(data['pages'][int(p) - 1])
else:
# 如果p不存在就是全集下載
cid_list = data['pages']
# print(cid_list)
for item in cid_list:
cid = str(item['cid'])
title = item['part']
title = re.sub(r'[\/\\:*?">|]', '', title) # 替換為空的
print('[下載視頻的cid]:' + cid)
print('[下載視頻的標(biāo)題]:' + title)
page = str(item['page'])
start_url = start_url + "/?p=" + page
video_list = get_play_list(aid, cid, quality)
start_time = time.time()
down_video(video_list, title, start_url, page)
combine_video(video_list, title)
# 如果是windows系統(tǒng),下載完成后打開(kāi)下載目錄
currentVideoPath = os.path.join(sys.path[0], 'bilibili_video') # 當(dāng)前目錄作為下載目錄
if (sys.platform.startswith('win')):
os.startfile(currentVideoPath)
# 分P視頻下載測(cè)試: https://www.bilibili.com/video/av19516333/
版本三: bilibili_video_download_v3.py
即版本二的升級(jí)版,為Threading多線程下載版本,下載速度大幅提升!
# !/usr/bin/python
# -*- coding:utf-8 -*-
# time: 2019/07/02--08:12
__author__ = 'Henry'
'''
項(xiàng)目: B站視頻下載 - 多線程下載
版本1: 加密API版,不需要加入cookie,直接即可下載1080p視頻
20190422 - 增加多P視頻單獨(dú)下載其中一集的功能
20190702 - 增加視頻多線程下載 速度大幅提升
'''
import requests, time, hashlib, urllib.request, re, json
from moviepy.editor import *
import os, sys, threading
import imageio
imageio.plugins.ffmpeg.download()
# 訪問(wèn)API地址
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=%scid=%sotype=jsonqn=%squality=%stype=' % (appkey, cid, quality, quality)
chksum = hashlib.md5(bytes(params + sec, 'utf8')).hexdigest()
url_api = 'https://interface.bilibili.com/v2/playurl?%ssign=%s' % (params, chksum)
headers = {
'Referer': start_url, # 注意加上referer
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
}
# print(url_api)
html = requests.get(url_api, headers=headers).json()
# print(json.dumps(html))
video_list = []
for i in html['durl']:
video_list.append(i['url'])
# print(video_list)
return video_list
# 下載視頻
'''
urllib.urlretrieve 的回調(diào)函數(shù):
def callbackfunc(blocknum, blocksize, totalsize):
@blocknum: 已經(jīng)下載的數(shù)據(jù)塊
@blocksize: 數(shù)據(jù)塊的大小
@totalsize: 遠(yuǎn)程文件的大小
'''
def Schedule_cmd(blocknum, blocksize, totalsize):
speed = (blocknum * blocksize) / (time.time() - start_time)
# speed_str = " Speed: %.2f" % speed
speed_str = " Speed: %s" % format_size(speed)
recv_size = blocknum * blocksize
# 設(shè)置下載進(jìn)度條
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()
# time.sleep(0.1)
f.write('\r')
def Schedule(blocknum, blocksize, totalsize):
speed = (blocknum * blocksize) / (time.time() - start_time)
# speed_str = " Speed: %.2f" % speed
speed_str = " Speed: %s" % format_size(speed)
recv_size = blocknum * blocksize
# 設(shè)置下載進(jìn)度條
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)
# print('\r')
# 字節(jié)bytes轉(zhuǎn)化K\M\G
def format_size(bytes):
try:
bytes = float(bytes)
kb = bytes / 1024
except:
print("傳入的字節(jié)格式不對(duì)")
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{}段視頻,請(qǐng)稍等...]:'.format(page) + title)
currentVideoPath = os.path.join(sys.path[0], 'bilibili_video', title) # 當(dāng)前目錄作為下載目錄
if not os.path.exists(currentVideoPath):
os.makedirs(currentVideoPath)
for i in video_list:
opener = urllib.request.build_opener()
# 請(qǐng)求頭
opener.addheaders = [
# ('Host', 'upos-hz-mirrorks3.acgvideo.com'), #注意修改host,不用也行
('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-'), # Range 的值要為 bytes=0- 才能下載完整視頻
('Referer', start_url), # 注意修改referer,必須要加的!
('Origin', 'https://www.bilibili.com'),
('Connection', 'keep-alive'),
]
urllib.request.install_opener(opener)
# 創(chuàng)建文件夾存放下載的視頻
if not os.path.exists(currentVideoPath):
os.makedirs(currentVideoPath)
# 開(kāi)始下載
if len(video_list) > 1:
urllib.request.urlretrieve(url=i, filename=os.path.join(currentVideoPath, r'{}-{}.flv'.format(title, num)),reporthook=Schedule_cmd) # 寫成mp4也行 title + '-' + num + '.flv'
else:
urllib.request.urlretrieve(url=i, filename=os.path.join(currentVideoPath, r'{}.flv'.format(title)),reporthook=Schedule_cmd) # 寫成mp4也行 title + '-' + num + '.flv'
num += 1
# 合并視頻(20190802新版)
def combine_video(title_list):
video_path = os.path.join(sys.path[0], 'bilibili_video') # 下載目錄
for title in title_list:
current_video_path = os.path.join(video_path ,title)
if len(os.listdir(current_video_path)) >= 2:
# 視頻大于一段才要合并
print('[下載完成,正在合并視頻...]:' + title)
# 定義一個(gè)數(shù)組
L = []
# 遍歷所有文件
for file in sorted(os.listdir(current_video_path), key=lambda x: int(x[x.rindex("-") + 1:x.rindex(".")])):
# 如果后綴名為 .mp4/.flv
if os.path.splitext(file)[1] == '.flv':
# 拼接成完整路徑
filePath = os.path.join(current_video_path, file)
# 載入視頻
video = VideoFileClip(filePath)
# 添加到數(shù)組
L.append(video)
# 拼接視頻
final_clip = concatenate_videoclips(L)
# 生成目標(biāo)視頻文件
final_clip.to_videofile(os.path.join(current_video_path, r'{}.mp4'.format(title)), fps=24, remove_temp=False)
print('[視頻合并完成]' + title)
else:
# 視頻只有一段則直接打印下載完成
print('[視頻合并完成]:' + title)
if __name__ == '__main__':
start_time = time.time()
# 用戶輸入av號(hào)或者視頻鏈接地址
print('*' * 30 + 'B站視頻下載小助手' + '*' * 30)
start = input('請(qǐng)輸入您要下載的B站av號(hào)或者視頻鏈接地址:')
if start.isdigit() == True: # 如果輸入的是av號(hào)
# 獲取cid的api, 傳入aid即可
start_url = 'https://api.bilibili.com/x/web-interface/view?aid=' + start
else:
# https://www.bilibili.com/video/av46958874/?spm_id_from=333.334.b_63686965665f7265636f6d6d656e64.16
start_url = 'https://api.bilibili.com/x/web-interface/view?aid=' + re.search(r'/av(\d+)/*', start).group(1)
# 視頻質(zhì)量
# accept_format>![CDATA[flv,flv720,flv480,flv360]]>/accept_format>
# accept_description>![CDATA[高清 1080P,高清 720P,清晰 480P,流暢 360P]]>/accept_description>
# accept_quality>![CDATA[80,64,32,16]]>/accept_quality>
quality = input('請(qǐng)輸入您要下載視頻的清晰度(1080p:80;720p:64;480p:32;360p:16)(填寫80或64或32或16):')
# 獲取視頻的cid,title
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:
# 單獨(dú)下載分P視頻中的一集
p = re.search(r'\&;p=(\d+)',start).group(1)
cid_list.append(data['pages'][int(p) - 1])
else:
# 如果p不存在就是全集下載
cid_list = data['pages']
# print(cid_list)
# 創(chuàng)建線程池
threadpool = []
title_list = []
for item in cid_list:
cid = str(item['cid'])
title = item['part']
title = re.sub(r'[\/\\:*?">|]', '', title) # 替換為空的
print('[下載視頻的cid]:' + cid)
print('[下載視頻的標(biāo)題]:' + title)
title_list.append(title)
page = str(item['page'])
start_url = start_url + "/?p=" + page
video_list = get_play_list(start_url, cid, quality)
start_time = time.time()
# down_video(video_list, title, start_url, page)
# 定義線程
th = threading.Thread(target=down_video, args=(video_list, title, start_url, page))
# 將線程加入線程池
threadpool.append(th)
# 開(kāi)始線程
for th in threadpool:
th.start()
# 等待所有線程運(yùn)行完畢
for th in threadpool:
th.join()
# 最后合并視頻
print(title_list)
combine_video(title_list)
end_time = time.time() # 結(jié)束時(shí)間
print('下載總耗時(shí)%.2f秒,約%.2f分鐘' % (end_time - start_time, int(end_time - start_time) / 60))
# 如果是windows系統(tǒng),下載完成后打開(kāi)下載目錄
currentVideoPath = os.path.join(sys.path[0], 'bilibili_video') # 當(dāng)前目錄作為下載目錄
if (sys.platform.startswith('win')):
os.startfile(currentVideoPath)
# 分P視頻下載測(cè)試: https://www.bilibili.com/video/av19516333/
# 下載總耗時(shí)14.21秒,約0.23分鐘
版本四: GUI版本 - bilibili_video_download-GUI.py
# !/usr/bin/python
# -*- coding:utf-8 -*-
# time: 2019/07/02--08:12
__author__ = 'Henry'
'''
項(xiàng)目: B站視頻下載 - GUI版本
版本1: 加密API版,不需要加入cookie,直接即可下載1080p視頻
20190422 - 增加多P視頻單獨(dú)下載其中一集的功能
20190702 - 增加視頻多線程下載 速度大幅提升
20190711 - 增加GUI版本,可視化界面,操作更加友好
'''
import requests, time, hashlib, urllib.request, re, json
import imageio
imageio.plugins.ffmpeg.download()
from moviepy.editor import *
import os, sys, threading
from tkinter import *
from tkinter import ttk
from tkinter import StringVar
root=Tk()
start_time = time.time()
# 將輸出重定向到表格
def print(theText):
msgbox.insert(END,theText+'\n')
# 訪問(wèn)API地址
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=%scid=%sotype=jsonqn=%squality=%stype=' % (appkey, cid, quality, quality)
chksum = hashlib.md5(bytes(params + sec, 'utf8')).hexdigest()
url_api = 'https://interface.bilibili.com/v2/playurl?%ssign=%s' % (params, chksum)
headers = {
'Referer': start_url, # 注意加上referer
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
}
# print(url_api)
html = requests.get(url_api, headers=headers).json()
# print(json.dumps(html))
video_list = []
for i in html['durl']:
video_list.append(i['url'])
# print(video_list)
return video_list
# 下載視頻
'''
urllib.urlretrieve 的回調(diào)函數(shù):
def callbackfunc(blocknum, blocksize, totalsize):
@blocknum: 已經(jīng)下載的數(shù)據(jù)塊
@blocksize: 數(shù)據(jù)塊的大小
@totalsize: 遠(yuǎn)程文件的大小
'''
def Schedule_cmd(blocknum, blocksize, totalsize):
speed = (blocknum * blocksize) / (time.time() - start_time)
# speed_str = " Speed: %.2f" % speed
speed_str = " Speed: %s" % format_size(speed)
recv_size = blocknum * blocksize
# 設(shè)置下載進(jìn)度條
pervent = recv_size / totalsize
percent_str = "%.2f%%" % (pervent * 100)
download.coords(fill_line1,(0,0,pervent*465,23))
root.update()
pct.set(percent_str)
def Schedule(blocknum, blocksize, totalsize):
speed = (blocknum * blocksize) / (time.time() - start_time)
# speed_str = " Speed: %.2f" % speed
speed_str = " Speed: %s" % format_size(speed)
recv_size = blocknum * blocksize
# 設(shè)置下載進(jìn)度條
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)
# print('\r')
# 字節(jié)bytes轉(zhuǎn)化K\M\G
def format_size(bytes):
try:
bytes = float(bytes)
kb = bytes / 1024
except:
print("傳入的字節(jié)格式不對(duì)")
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{}段視頻,請(qǐng)稍等...]:'.format(page) + title)
currentVideoPath = os.path.join(sys.path[0], 'bilibili_video', title) # 當(dāng)前目錄作為下載目錄
for i in video_list:
opener = urllib.request.build_opener()
# 請(qǐng)求頭
opener.addheaders = [
# ('Host', 'upos-hz-mirrorks3.acgvideo.com'), #注意修改host,不用也行
('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-'), # Range 的值要為 bytes=0- 才能下載完整視頻
('Referer', start_url), # 注意修改referer,必須要加的!
('Origin', 'https://www.bilibili.com'),
('Connection', 'keep-alive'),
]
urllib.request.install_opener(opener)
# 創(chuàng)建文件夾存放下載的視頻
if not os.path.exists(currentVideoPath):
os.makedirs(currentVideoPath)
# 開(kāi)始下載
if len(video_list) > 1:
urllib.request.urlretrieve(url=i, filename=os.path.join(currentVideoPath, r'{}-{}.flv'.format(title, num)),reporthook=Schedule_cmd) # 寫成mp4也行 title + '-' + num + '.flv'
else:
urllib.request.urlretrieve(url=i, filename=os.path.join(currentVideoPath, r'{}.flv'.format(title)),reporthook=Schedule_cmd) # 寫成mp4也行 title + '-' + num + '.flv'
num += 1
# 合并視頻(20190802新版)
def combine_video(title_list):
video_path = os.path.join(sys.path[0], 'bilibili_video') # 下載目錄
for title in title_list:
current_video_path = os.path.join(video_path ,title)
if len(os.listdir(current_video_path)) >= 2:
# 視頻大于一段才要合并
print('[下載完成,正在合并視頻...]:' + title)
# 定義一個(gè)數(shù)組
L = []
# 遍歷所有文件
for file in sorted(os.listdir(current_video_path), key=lambda x: int(x[x.rindex("-") + 1:x.rindex(".")])):
# 如果后綴名為 .mp4/.flv
if os.path.splitext(file)[1] == '.flv':
# 拼接成完整路徑
filePath = os.path.join(current_video_path, file)
# 載入視頻
video = VideoFileClip(filePath)
# 添加到數(shù)組
L.append(video)
# 拼接視頻
final_clip = concatenate_videoclips(L)
# 生成目標(biāo)視頻文件
final_clip.to_videofile(os.path.join(current_video_path, r'{}.mp4'.format(title)), fps=24, remove_temp=False)
print('[視頻合并完成]' + title)
else:
# 視頻只有一段則直接打印下載完成
print('[視頻合并完成]:' + title)
def do_prepare(inputStart,inputQuality):
# 清空進(jìn)度條
download.coords(fill_line1,(0,0,0,23))
pct.set('0.00%')
root.update()
# 清空文本欄
msgbox.delete('1.0','end')
start_time = time.time()
# 用戶輸入av號(hào)或者視頻鏈接地址
print('*' * 30 + 'B站視頻下載小助手' + '*' * 30)
start = inputStart
if start.isdigit() == True: # 如果輸入的是av號(hào)
# 獲取cid的api, 傳入aid即可
start_url = 'https://api.bilibili.com/x/web-interface/view?aid=' + start
else:
# https://www.bilibili.com/video/av46958874/?spm_id_from=333.334.b_63686965665f7265636f6d6d656e64.16
start_url = 'https://api.bilibili.com/x/web-interface/view?aid=' + re.search(r'/av(\d+)/*', start).group(1)
# 視頻質(zhì)量
# accept_format>![CDATA[flv,flv720,flv480,flv360]]>/accept_format>
# accept_description>![CDATA[高清 1080P,高清 720P,清晰 480P,流暢 360P]]>/accept_description>
# accept_quality>![CDATA[80,64,32,16]]>/accept_quality>
quality = inputQuality
# 獲取視頻的cid,title
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:
# 單獨(dú)下載分P視頻中的一集
p = re.search(r'\&;p=(\d+)',start).group(1)
cid_list.append(data['pages'][int(p) - 1])
else:
# 如果p不存在就是全集下載
cid_list = data['pages']
# print(cid_list)
# 創(chuàng)建線程池
threadpool = []
title_list = []
for item in cid_list:
cid = str(item['cid'])
title = item['part']
title = re.sub(r'[\/\\:*?">|]', '', title) # 替換為空的
print('[下載視頻的cid]:' + cid)
print('[下載視頻的標(biāo)題]:' + title)
title_list.append(title)
page = str(item['page'])
start_url = start_url + "/?p=" + page
video_list = get_play_list(start_url, cid, quality)
start_time = time.time()
# down_video(video_list, title, start_url, page)
# 定義線程
th = threading.Thread(target=down_video, args=(video_list, title, start_url, page))
# 將線程加入線程池
threadpool.append(th)
# 開(kāi)始線程
for th in threadpool:
th.start()
# 等待所有線程運(yùn)行完畢
for th in threadpool:
th.join()
# 最后合并視頻
combine_video(title_list)
end_time = time.time() # 結(jié)束時(shí)間
print('下載總耗時(shí)%.2f秒,約%.2f分鐘' % (end_time - start_time, int(end_time - start_time) / 60))
# 如果是windows系統(tǒng),下載完成后打開(kāi)下載目錄
currentVideoPath = os.path.join(sys.path[0], 'bilibili_video') # 當(dāng)前目錄作為下載目錄
if (sys.platform.startswith('win')):
os.startfile(currentVideoPath)
def thread_it(func, *args):
'''將函數(shù)打包進(jìn)線程'''
# 創(chuàng)建
t = threading.Thread(target=func, args=args)
# 守護(hù) !!!
t.setDaemon(True)
# 啟動(dòng)
t.start()
if __name__ == "__main__":
# 設(shè)置標(biāo)題
root.title('B站視頻下載小助手-GUI')
# 設(shè)置ico
root.iconbitmap('./Pic/favicon.ico')
# 設(shè)置Logo
photo = PhotoImage(file='./Pic/logo.png')
logo = Label(root,image=photo)
logo.pack()
# 各項(xiàng)輸入欄和選擇框
inputStart = Entry(root,bd=4,width=600)
labelStart=Label(root,text="請(qǐng)輸入您要下載的B站av號(hào)或者視頻鏈接地址:") # 地址輸入
labelStart.pack(anchor="w")
inputStart.pack()
labelQual = Label(root,text="請(qǐng)選擇您要下載視頻的清晰度") # 清晰度選擇
labelQual.pack(anchor="w")
inputQual = ttk.Combobox(root,state="readonly")
# 可供選擇的表
inputQual['value']=('1080P','720p','480p','360p')
# 對(duì)應(yīng)的轉(zhuǎn)換字典
keyTrans=dict()
keyTrans['1080P']='80'
keyTrans['720p']='64'
keyTrans['480p']='32'
keyTrans['360p']='16'
# 初始值為720p
inputQual.current(1)
inputQual.pack()
confirm = Button(root,text="開(kāi)始下載",command=lambda:thread_it(do_prepare,inputStart.get(), keyTrans[inputQual.get()] ))
msgbox = Text(root)
msgbox.insert('1.0',"對(duì)于單P視頻:直接傳入B站av號(hào)或者視頻鏈接地址\n(eg: 49842011或者h(yuǎn)ttps://www.bilibili.com/video/av49842011)\n對(duì)于多P視頻:\n1.下載全集:直接傳入B站av號(hào)或者視頻鏈接地址\n(eg: 49842011或者h(yuǎn)ttps://www.bilibili.com/video/av49842011)\n2.下載其中一集:傳入那一集的視頻鏈接地址\n(eg: https://www.bilibili.com/video/av19516333/?p=2)")
msgbox.pack()
download=Canvas(root,width=465,height=23,bg="white")
# 進(jìn)度條的設(shè)置
labelDownload=Label(root,text="下載進(jìn)度")
labelDownload.pack(anchor="w")
download.pack()
fill_line1 = download.create_rectangle(0, 0, 0, 23, width=0, fill="green")
pct=StringVar()
pct.set('0.0%')
pctLabel = Label(root,textvariable=pct)
pctLabel.pack()
root.geometry("600x800")
confirm.pack()
# GUI主循環(huán)
root.mainloop()
版本五: bilibili_video_download_bangumi.py
在版本一,三基礎(chǔ)上增加下載B站番劇視頻(eg: https://www.bilibili.com/bangumi/play/ep269835)
# !/usr/bin/python
# -*- coding:utf-8 -*-
# time: 2019/07/21--20:12
__author__ = 'Henry'
'''
項(xiàng)目: B站動(dòng)漫番劇(bangumi)下載
版本2: 無(wú)加密API版,但是需要加入登錄后cookie中的SESSDATA字段,才可下載720p及以上視頻
API:
1.獲取cid的api為 https://api.bilibili.com/x/web-interface/view?aid=47476691 aid后面為av號(hào)
2.下載鏈接api為 https://api.bilibili.com/x/player/playurl?avid=44743619cid=78328965qn=32 cid為上面獲取到的 avid為輸入的av號(hào) qn為視頻質(zhì)量
注意:
但是此接口headers需要加上登錄后'Cookie': 'SESSDATA=3c5d20cf%2C1556704080%2C7dcd8c41' (30天的有效期)(因?yàn)楝F(xiàn)在只有登錄后才能看到720P以上視頻了)
不然下載之后都是最低清晰度,哪怕選擇了80也是只有480p的分辨率!!
'''
import requests, time, urllib.request, re
from moviepy.editor import *
import os, sys, threading, json
import imageio
imageio.plugins.ffmpeg.download()
# 訪問(wèn)API地址
def get_play_list(aid, cid, quality):
url_api = 'https://api.bilibili.com/x/player/playurl?cid={}avid={}qn={}'.format(cid, aid, quality)
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',
'Cookie': 'SESSDATA=75a75cf2%2C1564669876%2Cb7c7b171', # 登錄B站后復(fù)制一下cookie中的SESSDATA字段,有效期1個(gè)月
'Host': 'api.bilibili.com'
}
html = requests.get(url_api, headers=headers).json()
# print(html)
# 當(dāng)下載會(huì)員視頻時(shí),如果cookie中傳入的不是大會(huì)員的SESSDATA時(shí)就會(huì)返回: {'code': -404, 'message': '啥都木有', 'ttl': 1, 'data': None}
if html['code'] != 0:
print('注意!當(dāng)前集數(shù)為B站大會(huì)員專享,若想下載,Cookie中請(qǐng)傳入大會(huì)員的SESSDATA')
return 'NoVIP'
video_list = []
for i in html['data']['durl']:
video_list.append(i['url'])
print(video_list)
return video_list
# 下載視頻
'''
urllib.urlretrieve 的回調(diào)函數(shù):
def callbackfunc(blocknum, blocksize, totalsize):
@blocknum: 已經(jīng)下載的數(shù)據(jù)塊
@blocksize: 數(shù)據(jù)塊的大小
@totalsize: 遠(yuǎn)程文件的大小
'''
def Schedule_cmd(blocknum, blocksize, totalsize):
speed = (blocknum * blocksize) / (time.time() - start_time)
# speed_str = " Speed: %.2f" % speed
speed_str = " Speed: %s" % format_size(speed)
recv_size = blocknum * blocksize
# 設(shè)置下載進(jìn)度條
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()
# time.sleep(0.1)
f.write('\r')
def Schedule(blocknum, blocksize, totalsize):
speed = (blocknum * blocksize) / (time.time() - start_time)
# speed_str = " Speed: %.2f" % speed
speed_str = " Speed: %s" % format_size(speed)
recv_size = blocknum * blocksize
# 設(shè)置下載進(jìn)度條
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)
# print('\r')
# 字節(jié)bytes轉(zhuǎn)化K\M\G
def format_size(bytes):
try:
bytes = float(bytes)
kb = bytes / 1024
except:
print("傳入的字節(jié)格式不對(duì)")
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('[正在下載第{}話視頻,請(qǐng)稍等...]:'.format(page) + title)
currentVideoPath = os.path.join(sys.path[0], 'bilibili_video', title) # 當(dāng)前目錄作為下載目錄
for i in video_list:
opener = urllib.request.build_opener()
# 請(qǐng)求頭
opener.addheaders = [
# ('Host', 'upos-hz-mirrorks3.acgvideo.com'), #注意修改host,不用也行
('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-'), # Range 的值要為 bytes=0- 才能下載完整視頻
('Referer', start_url), # 注意修改referer,必須要加的!
('Origin', 'https://www.bilibili.com'),
('Connection', 'keep-alive'),
]
urllib.request.install_opener(opener)
# 創(chuàng)建文件夾存放下載的視頻
if not os.path.exists(currentVideoPath):
os.makedirs(currentVideoPath)
# 開(kāi)始下載
if len(video_list) > 1:
urllib.request.urlretrieve(url=i, filename=os.path.join(currentVideoPath, r'{}-{}.flv'.format(title, num)),
reporthook=Schedule_cmd) # 寫成mp4也行 title + '-' + num + '.flv'
else:
urllib.request.urlretrieve(url=i, filename=os.path.join(currentVideoPath, r'{}.flv'.format(title)),
reporthook=Schedule_cmd) # 寫成mp4也行 title + '-' + num + '.flv'
num += 1
# 合并視頻(20190802新版)
def combine_video(title_list):
video_path = os.path.join(sys.path[0], 'bilibili_video') # 下載目錄
for title in title_list:
current_video_path = os.path.join(video_path ,title)
if len(os.listdir(current_video_path)) >= 2:
# 視頻大于一段才要合并
print('[下載完成,正在合并視頻...]:' + title)
# 定義一個(gè)數(shù)組
L = []
# 遍歷所有文件
for file in sorted(os.listdir(current_video_path), key=lambda x: int(x[x.rindex("-") + 1:x.rindex(".")])):
# 如果后綴名為 .mp4/.flv
if os.path.splitext(file)[1] == '.flv':
# 拼接成完整路徑
filePath = os.path.join(current_video_path, file)
# 載入視頻
video = VideoFileClip(filePath)
# 添加到數(shù)組
L.append(video)
# 拼接視頻
final_clip = concatenate_videoclips(L)
# 生成目標(biāo)視頻文件
final_clip.to_videofile(os.path.join(current_video_path, r'{}.mp4'.format(title)), fps=24, remove_temp=False)
print('[視頻合并完成]' + title)
else:
# 視頻只有一段則直接打印下載完成
print('[視頻合并完成]:' + title)
if __name__ == '__main__':
start_time = time.time()
# 用戶輸入番劇完整鏈接地址
# 1. https://www.bilibili.com/bangumi/play/ep267692 (用帶ep鏈接)
# 2. https://www.bilibili.com/bangumi/play/ss26878 (不要用這個(gè)ss鏈接,epinfo的aid會(huì)變成'-1')
print('*' * 30 + 'B站番劇視頻下載小助手' + '*' * 30)
print('[提示]: 1.如果您想下載720P60,1080p+,1080p60質(zhì)量的視頻,請(qǐng)將35行代碼中的SESSDATA改成你登錄大會(huì)員后得到的SESSDATA,普通用戶的SESSDATA最多只能下載1080p的視頻')
print(' 2.若發(fā)現(xiàn)下載的視頻質(zhì)量在720p以下,請(qǐng)將35行代碼中的SESSDATA改成你登錄后得到的SESSDATA(有效期一個(gè)月),而失效的SESSDATA就只能下載480p的視頻')
start = input('請(qǐng)輸入您要下載的B站番劇的完整鏈接地址(例如:https://www.bilibili.com/bangumi/play/ep267692):')
ep_url = start
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(ep_url,headers=headers).text
ep_info = re.search(r'INITIAL_STATE__=(.*?"]});', html).group(1)
# print(ep_info)
ep_info = json.loads(ep_info)
# print('您將要下載的番劇名為:' + ep_info['mediaInfo']['title']) # 字段格式太不統(tǒng)一了
y = input('請(qǐng)輸入1或2 - 1.只下載當(dāng)前一集 2.下載此番劇的全集:')
# 1.如果只下載當(dāng)前ep
id_list = []
if y == '1':
try:
id_list.append([ep_info['epInfo']['aid'], ep_info['epInfo']['cid'],
ep_info['epInfo']['titleFormat'] + ' ' + ep_info['epInfo']['longTitle']])
except:
id_list.append([ep_info['epInfo']['aid'], ep_info['epInfo']['cid'],
'第' + str(ep_info['epInfo']['index']) + '話 ' + ep_info['epInfo']['index_title']])
# 2.下載此番劇全部ep
else:
for i in ep_info['epList']:
# if i['badge'] == '': # 當(dāng)badge字段為'會(huì)員'時(shí),接口返回404
try:
id_list.append([i['aid'], i['cid'],
i['titleFormat'] + ' ' + i['longTitle']])
except:
id_list.append([i['aid'], i['cid'],'第' + str(i['index']) + '話 ' + i['index_title']])
# qn參數(shù)就是視頻清晰度
# 可選值:
# 116: 高清1080P60 (需要帶入大會(huì)員的cookie中的SESSDATA才行,普通用戶的SESSDATA最多只能下載1080p的視頻,不帶入SESSDATA就只能下載480p的)
# 112: 高清1080P+ (hdflv2) (需要大會(huì)員)
# 80: 高清1080P (flv)
# 74: 高清720P60 (需要大會(huì)員)
# 64: 高清720P (flv720)
# 32: 清晰480P (flv480)
# 16: 流暢360P (flv360)
print('請(qǐng)輸入您要下載視頻的清晰度(1080p60:116;1080p+:112;1080p:80;720p60:74;720p:64;480p:32;360p:16; **注意:1080p+,1080p60,720p60都需要帶入大會(huì)員的cookie中的SESSDATA才行,普通用戶的SESSDATA最多只能下載1080p的視頻):')
quality = input('請(qǐng)輸入116或112或80或74或64或32或16:')
threadpool = []
title_list = []
page = 1
print(id_list)
for item in id_list:
aid = str(item[0])
cid = str(item[1])
title = item[2]
title = re.sub(r'[\/\\:*?">|]', '', title) # 替換為空的
print('[下載番劇標(biāo)題]:' + title)
title_list.append(title)
start_url = ep_url
video_list = get_play_list(aid, cid, quality)
start_time = time.time()
# down_video(video_list, title, start_url, page)
# 定義線程
if video_list != 'NoVIP':
th = threading.Thread(target=down_video, args=(video_list, title, start_url, page))
# 將線程加入線程池
threadpool.append(th)
page += 1
# 開(kāi)始線程
for th in threadpool:
th.start()
# 等待所有線程運(yùn)行完畢
for th in threadpool:
th.join()
# 最后合并視頻
print(title_list)
combine_video(title_list)
end_time = time.time() # 結(jié)束時(shí)間
print('下載總耗時(shí)%.2f秒,約%.2f分鐘' % (end_time - start_time, int(end_time - start_time) / 60))
# 如果是windows系統(tǒng),下載完成后打開(kāi)下載目錄
currentVideoPath = os.path.join(sys.path[0], 'bilibili_video') # 當(dāng)前目錄作為下載目錄
if (sys.platform.startswith('win')):
os.startfile(currentVideoPath)
# 番劇視頻下載測(cè)試: https://www.bilibili.com/bangumi/play/ep269828
以上就是python b站視頻下載的五種版本的詳細(xì)內(nèi)容,更多關(guān)于python b站視頻下載的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
您可能感興趣的文章:- 教你用Python下載抖音無(wú)水印視頻
- 教你如何使用Python下載B站視頻的詳細(xì)教程
- python基于tkinter制作m3u8視頻下載工具
- Python通過(guò)m3u8文件下載合并ts視頻的操作
- python gui開(kāi)發(fā)——制作抖音無(wú)水印視頻下載工具(附源碼)
- 用python制作個(gè)視頻下載器
- Python爬蟲進(jìn)階之爬取某視頻并下載的實(shí)現(xiàn)
- 利用python 下載bilibili視頻
- 寫一個(gè)Python腳本下載嗶哩嗶哩舞蹈區(qū)的所有視頻