python 下载 进度条
#1 【\r】要配合【print(printMsg, end='', flush=True)】的【flush】才能开头刷新
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | 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() |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
2017-08-21 python cookies 爬虫处理
2017-08-21 python 代理