Python3 使用requests模块显示下载http视频并且显示进度

效果图就不上了

用了才知道好

改了大半天

麻烦死了

上代码

import re
import urllib
import requests.packages.urllib3
import time
import os
from urllib.request import urlopen
import requests
from tqdm import tqdm

class Getfile():  #下载文件
    def __init__(self,url):
        self.url=url
        #self.filename=filename
        self.re=requests.head(url,allow_redirects=True)  #运行head方法时重定向
    def getsize(self):
        try:
            self.file_total=int(self.re.headers['Content-Length']) #获取下载文件大小
            return self.file_total
        except:
            print('无法获取下载文件大小'+ '\n'*2)
            exit()
    def getfilename(self):  #获取默认下载文件名
        filename=''
        if 'Content-Disposition' in self.re.headers:
            n=self.re.headers.get('Content-Disposition').split('name=')[1]
            filename=urllib.parse.unquote(n,encoding='utf8')
        elif os.path.splitext(self.re.url)[1]!='':
            filename=os.path.basename(self.re.url)
        return filename

def download_from_url(url, path):
    """
    @param: url to download file
    @param: dst place to put the file
    """
    file_size = int(urlopen(url).info().get('Content-Length', -1))

    if os.path.exists(path):
        first_byte = os.path.getsize(path)
    else:
        first_byte = 0
    if first_byte >= file_size:
        return file_size
    header = {"Range": "bytes=%s-%s" % (first_byte, file_size)}
    pbar = tqdm(
        total=file_size, initial=first_byte,
        unit='B', unit_scale=True, desc='progress:')
    req = requests.get(url, headers=header, stream=True)
    with(open(path, 'wb')) as f:
        for chunk in req.iter_content(chunk_size=1024):
            if chunk:
                f.write(chunk)
                pbar.update(1024)
    pbar.close()
    return file_size

if __name__ == '__main__':
    url = input('请输入地址:')
    while not re.match('^(https?|ftp)://.+$',url):
        url = input("网址格式错误,请重新输入:")
    file1=Getfile(url)
    file_total=file1.getsize()
    filename=file1.getfilename()
    if filename=='':
        filename=input('无法获取下载文件名,请自行输入:')
    print ("下载的文件为:"+str('%.2f' % (file_total/1024/1024))+"MB"+ '\n'*2)
    print ("开始下载文件:"+filename)
    filename_strip = filename.strip()[1:-1]
    download_from_url(url, 'E:/000000/'+ filename_strip)
    print(filename_strip + ' 下载成功!' + '\n'*2 + '10s后退出窗口')#非cmd或linux运行可注释掉
    time.sleep(10)

发表评论

Connect with