生活随笔
收集整理的這篇文章主要介紹了
python 使用requests模块进行 视频文件的下载
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
公司項目需要下載一批視頻文件, 格式是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:passfsize1 = 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-' % fsize1resp = 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 = Falsereturn real_video_download_pathelse:# 出現異常time.sleep(3)breakexcept Exception as e:print(e.args)else:break
總結
以上是生活随笔為你收集整理的python 使用requests模块进行 视频文件的下载的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。