How to download an online video stream using python

在进行爬虫的时候,经常需要保存视频到本地。通常得先获得视频(.mp4)的下载链接,再设置保存到本地的路径(路径包括最后的命名,例如:D:/1.mp4),因此函数传入的参数为url和path。

注:这里面用到requests和os库

import os,import requests。
def download_video(url, file_path):
    try:
        headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/4.3.2.1000 Chrome/30.0.1599.101 Safari/537.36"}
        pre_content_length = 0
        # 循环接收视频数据
        while True:# 若文件已经存在,则断点续传,设置接收来需接收数据的位置    
            if os.path.exists(file_path):
                headers['Range'] = 'bytes=%d-' % os.path.getsize(file_path)
            res = requests.get(url, stream=True, headers=headers)
            content_length = int(res.headers['content-length'])
            # 若当前报文长度小于前次报文长度,或者已接收文件等于当前报文长度,则可以认为视频接收完成
            if content_length < pre_content_length or (os.path.exists(file_path) and os.path.getsize(file_path) >= content_length):
                break
            pre_content_length = content_length
            # 写入收到的视频数据
            with open(file_path, 'ab') as file:
                file.write(res.content)
                file.flush()
                print('receive data,file size : %d   total size:%d' % (os.path.getsize(file_path), content_length))
    except Exception as e:
        dic = {'url':url, 'file_path':file_path}
        print("下载失败:", dic)
发布了254 篇原创文章 · 获赞 31 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/yueliang2100/article/details/103995949