【python 】文件下载进度条(装逼利器)
- 基础版
import requests url = "http://mp.111ttt.cn/mp3free/81135985.mp3" rsp = requests.get(url, stream=True) with open(‘1.mp3‘, ‘wb‘) as f: for i in rsp.iter_content(chunk_size=1024): # 边下载边存硬盘, chunk_size 可以自由调整为可以更好地适合您的用例的数字 f.write(i)
- 晋级版
# 下载MP3文件到本地 import os import requests def DownloadFile(mp3_url, save_url,file_name): try: if mp3_url is None or save_url is None or file_name is None: print(‘参数错误‘) return None # 文件夹不存在,则创建文件夹 folder = os.path.exists(save_url) if not folder: os.makedirs(save_url) # 读取MP3资源 res = requests.get(mp3_url,stream=True) # 获取文件地址 file_path = os.path.join(save_url, file_name) print(‘开始写入文件:‘, file_path) # 打开本地文件夹路径file_path,以二进制流方式写入,保存到本地 with open(file_path, ‘wb‘) as fd: for chunk in res.iter_content(chunk_size=1024): fd.write(chunk) print(file_name+‘ 成功下载!‘) except: print("程序错误")
if __name__ == "__main__": # MP3源地址url url = ‘http://mp.111ttt.cn/mp3free/81135985.mp3‘ # MP3保存文件夹 save_url=‘./music/‘ # MP3文件名 file_name = ‘mymusic‘+‘.mp3‘ DownloadFile(url,save_url, file_name)
- 升级版
def DownloadFile2(mp3_url, save_url,file_name): try: if mp3_url is None or save_url is None or file_name is None: print(‘参数错误‘) return None # 文件夹不存在,则创建文件夹 folder = os.path.exists(save_url) if not folder: os.makedirs(save_url) # 读取MP3资源 res = requests.get(mp3_url,stream=True) total_size = int(int(res.headers["Content-Length"])/1024+0.5) # 获取文件地址 file_path = os.path.join(save_url, file_name) # 打开本地文件夹路径file_path,以二进制流方式写入,保存到本地 from tqdm import tqdm with open(file_path, ‘wb‘) as fd: print(‘开始下载文件:{},当前文件大小:{}KB‘.format(file_name,total_size)) for chunk in tqdm(iterable=res.iter_content(1024),total=total_size,unit=‘k‘,desc=None): fd.write(chunk) print(file_name+‘ 下载完成!‘) except: print("程序错误")
# MP3源地址url mp3_url = ‘http://mp.111ttt.cn/mp3free/81135985.mp3‘ # MP3保存文件夹 save_url=‘./music/‘ # MP3文件名 file_name = ‘少年-梦然.mp3‘ DownloadFile2(mp3_url,save_url, file_name)
- 装逼版
for file_name,mp3_url in zip(musicnamelst[:2],musicurllst[:2]): DownloadFile2(mp3_url,save_url, file_name+‘.mp3‘)
如果要全量下载,去掉索引
for file_name,mp3_url in zip(musicnamelst,musicurllst): DownloadFile2(mp3_url,save_url, file_name+‘.mp3‘)
太多了,部分截图
相关推荐
想个标题偏头痛 2020-04-09
LeoQ 2019-08-08
xiaxiaoyule 2013-06-20
移动视频探索者 2019-07-01
流萤 2019-06-28
mingrixing 2019-06-28
huzijia 2012-01-31
linvaluable 2015-09-25
SILENCEWCHEN 2012-10-16
85281245 2017-05-08
89447715 2012-07-06
89570195 2012-06-06
vianowu 2011-05-26
shao 2011-01-24
only0 2017-06-07
dengfan 2017-04-19
yjreset 2015-02-11
zhaojikun 2015-06-15