python 下载 进度条


#1 【\r】要配合【print(printMsg, end='', flush=True)】的【flush】才能开头刷新

import os
import requests
import time

# 进度条模块
def progressbar(url,path):
    if not os.path.exists(path):   # 看是否有该文件夹,没有则创建文件夹
         os.mkdir(path)
    start = time.time() #下载开始时间
    response = requests.get(url, stream=True)
    size = 0    #初始化已下载大小
    chunk_size = 1024  # 每次下载的数据大小
    content_size = int(response.headers['content-length'])  # 下载文件总大小
    try:
        if response.status_code != 200:   #判断是否响应成功
            print("response.status_code != 200")
            return 0
        if response.status_code == 200:   #判断是否响应成功
            print('Start download,[File size]:{size:.2f} MB'.format(size = content_size / chunk_size /1024))   #开始下载,显示下载文件大小
            filepath = r'{}\{}'.format(path,url[-5:])  #设置图片name,注:必须加上扩展名
            # filepath =r'D:\tmp\images\123.jpg'
            # print('filepath=========='+filepath)
            with open(filepath,'wb') as file:   #显示进度条
                # print("+"*10)
                for data in response.iter_content(chunk_size = chunk_size):

                    file.write(data)
                    size +=len(data)
                    # time.sleep(0.5)
                    # print('\r'+'[download]:%s%.2f%%' % ('>'*int(size*50/ content_size), float(size / content_size * 100)) ,end=' ')
                    msg='\r{}{:.2f}% '.format ('>'*int(size*50/ content_size), float(size / content_size * 100))
                    # \r 就是每次打印回到行最开头
                    print(msg ,end='', flush=True)
        end = time.time()   #下载结束时间
        print('\nDownload completed!,times: %.2fs' % (end - start), end='', flush=True)  #输出下载用时时间
    except:
        print('Error!')

def main():
    #下载皮卡丘图片
    url = 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1783995481,3672177359&fm=26&gp=0.jpg'
    # print("url[-10,-1]========="+url[-10:])
    path = r'D:\tmp\images'  # 设置下载到本地的地址
    progressbar(url,path)

if __name__ == '__main__':
    main()