公司項目需要下載一批視頻文件, 格式是mp4和mkv的,就藉助request模塊進行了下載,前提是源服務器返回文件的大小,以及可以接受 請求頭headers中帶有Range參數
以下是下載邏輯:
resp = requests.head(url=real_video_url)
headers = {}
try:
totalfilesize = int(resp.headers['Content-Length'])
except Exception as e:
print(e.args)
if not os.path.exists(real_video_download_path):
with open(real_video_download_path, 'ab+') as f:
pass
fsize1 = os.path.getsize(real_video_download_path)
flag = True
while True:
if flag:
try:
fsize1 = os.path.getsize(real_video_download_path)
headers['Range'] = 'bytes=%d-' % fsize1
resp = requests.get(url=real_video_url, headers=headers, stream=True, timeout=20)
with open(real_video_download_path, 'ab+') as f:
for chunk in resp.iter_content(chunk_size=4096):
if resp.status_code == 206:
if chunk:
f.write(chunk)
elif os.path.getsize(real_video_download_path) >= totalfilesize:
# 出現這種情況,就說明已經下載完畢
flag = False
return real_video_download_path
else:
# 出現異常
time.sleep(3)
break
except Exception as e:
print(e.args)
else:
break