MP4链接下载

import requests
from contextlib import closing
url = 'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4'
path = 'test_video.mp4'
#下载视频链接的最简单方法
''' r = requests.get(url, stream=True) if r.status_code == 200: with open('test.mp4','wb')as f: for chunk in r.iter_content(chunk_size=1024*1024): if chunk: f.write(chunk) '''

#视频下载显示进度(须回车观察)
class ProgressBar(object):
    def __init__(self, title, count=0.0, run_status=None, fin_status=None, total=100.0, unit='', sep='/',
                 chunk_size=1.0):
        super(ProgressBar, self).__init__()
        self.info = "[%s] %s %.2f %s %s %.2f %s"
        self.title = title
        self.total = total
        self.count = count
        self.chunk_size = chunk_size
        self.status = run_status or ""
        self.fin_status = fin_status or " " * len(self.statue)
        self.unit = unit
        self.seq = sep

    def __get_info(self):
        # 【名称】状态 进度 单位 分割线 总数 单位
        _info = self.info % (
        self.title, self.status, self.count / self.chunk_size, self.unit, self.seq, self.total / self.chunk_size,
        self.unit)
        return _info

    def refresh(self, count=1, status=None):
        self.count += count
        # if status is not None:
        self.status = status or self.status
        end_str = "\r"
        if self.count >= self.total:
            end_str = '\n'
            self.status = status or self.fin_status
        print(self.__get_info(), end=end_str, )


def writedown(url, path):
    with closing(requests.get(url, stream=True)) as response:
        chunk_size = 1024
        content_size = int(response.headers['content-length'])
        progress = ProgressBar("razorback"
                               , total=content_size
                               , unit="KB"
                               , chunk_size=chunk_size
                               , run_status="正在下载"
                               , fin_status="下载完成")
        with open(path, "wb") as file:
            for data in response.iter_content(chunk_size=chunk_size):
                if(data):
                    file.write(data)
                    progress.refresh(count=len(data))

if __name__=='__main__':
    writedown(url,path)

你可能感兴趣的:(MP4链接下载)