微信咨询

微信咨询

13610*910*9

服务热线 7*24小时

电话咨询

python+tqdm 实现图片音视频下载进度条显示

iamdu2019-12-15 22:38:19 浏览: 617758
from tqdm import tqdm
import time,requests

def downloadFILE(url,name):
    res = requests.get(url=url,stream=True)
    #stream=True的作用是仅让响应头被下载,连接保持打开状态,
    content_size = int(res.headers['Content-Length'])/1024
    with open(name, "wb") as f:
        print("文件包整个大小是:",'%.2f' %(content_size/1024),'mb','开始下载...')
        for data in tqdm(iterable=res.iter_content(1024),total=content_size,unit='k',desc=name,ascii=True):
        #调用iter_content,一块一块的遍历要下载的内容,搭配stream=True,此时才开始真正的下载
        #iterable:可迭代的进度条 total:总的迭代次数 desc:进度条的前缀
            f.write(data)
        print(name + "下载完成!")
if __name__ == '__main__':
    url = "https://tbm-auth.alicdn.com/e99361edd833010b/Fyi1cVXfmne85HEi1Qs/FN3Xbv73dMtsc9Ud0KL_229411455098_hd_hq.mp4?auth_key=1576422532-0-0-bd639a98e5a6140128eee9ffeaf91c43"
    name2 = url.split('?')[-2]       #截取整个地址?前的地址
    name = name2.split('/')[-1]      #把截取后的地址获得最后一个/后的名字 即ChiWIcs8sCDq0vIF8ZP_229323118648_hd_hq.mp4
    downloadFILE(url,name)