目前的问题就是下载速度有点慢,没有添加多线程
1 import requests
2 from contextlib import closing
3
4 def downlaod(url):
5 '''核心下载代码'''
6 with requests.Session() as s:
7 headers = {
8 'Accept':'*/*',
9 'Accept-Encoding':'gzip, deflate, br',
10 'Accept-Language':'zh-CN,zh;q=0.9',
11 'Connection':'keep-alive',
12 'Host':'cn-hbsjz2-cmcc-acache-04.acgvideo.com',
13 'If-Range':'Mon, 07 Jan 2019 03:35:04 GMT',
14 'Origin':'https://www.bilibili.com',
15 'Range':'bytes=0-974',
16 'Referer':'https://www.bilibili.com/video/av40081185/', # 跳转页面,可以修改
17 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
18 }
19 s.headers = headers
20 with closing(s.get(url,stream=True)) as response: # 为了获得视频的总大小
21 content_size = int(response.headers['Content-Range'].split('/')[-1]) # 视频的总大小
22 count = content_size // 5000 # 把总大小分成多少块
23 chunk_size = 5000 # 把块大小设定为5000
24 total = 0
25 a = 0
26 with open('./file.mp4', "ab+") as file:
27 for i in range(count):
28 total += chunk_size
29 if total < content_size: # 满足每块5000字节时下载
30 data = s.get(url,headers={'Range':'bytes=%s-%s'%(a,total)}) # 构造请求头
31 file.write(data.content)
32 else: # 块大小小于5000时调用
33 data = s.get(url,headers={'Range':'bytes=%s-%s'%(a,content_size-chunk_size*count)})
34 file.write(data.content)
35 a = (i + 1) * chunk_size + 1