1 importos2 importrequests3 importtime4
5
6 #进度条模块
7 defprogressbar(url, path):8 if not os.path.exists(path): #看是否有该文件夹,没有则创建文件夹
9os.mkdir(path)10 start = time.time() #下载开始时间
11 response = requests.get(url, stream=True)12 size = 0 #初始化已下载大小
13 chunk_size = 1024 #每次下载的数据大小
14 content_size = int(response.headers['content-length']) #下载文件总大小
15 try:16 if response.status_code == 200: #判断是否响应成功
17 #开始下载,显示下载文件大小
18 print('Start download,[File size]:{size:.2f} MB'.format(size=content_size / chunk_size / 1024))19 filepath = path+'\Pikachu.jpg' #设置图片name,注:必须加上扩展名
20 with open(filepath, 'wb') as file: #显示进度条
21 for data in response.iter_content(chunk_size=chunk_size):22file.write(data)23 size +=len(data)24 print('\r'+'[下载进度]:%s%.2f%%' % ('>'*int(size*50 /content_size),25 float(size / content_size * 100)), end=' ')26 end = time.time() #下载结束时间
27 print('Download completed!,times: %.2f秒' % (end - start)) #输出下载用时时间
28 except:29 print('Error!')