[Python] 纯文本查看 复制代码 def download(name,interval=0.5):
def MB(byte):
return byte / 1024 / 1024
print(name)
res = requests.get(link_sec,params=params,headers=headers,stream=True,allow_redirects=True)
file_size = int(res.headers['Content-Length'])
print(file_size)# 文件大小 Byte
f = open(name, 'wb')
down_size = 0 # 已下载字节数
old_down_size = 0 # 上一次已下载字节数
time_ = time.time()
for chunk in res.iter_content(chunk_size=512):
if chunk:
f.write(chunk)
down_size += len(chunk)
if time.time() - time_ > interval:
# rate = down_size / file_size * 100 # 进度 0.01%
speed = (down_size - old_down_size) / interval # 速率 0.01B/s
old_down_size = down_size
time_ = time.time()
print_params = [MB(speed), MB(down_size), MB(file_size), (file_size - down_size) / speed ]
print('\r{:.1f}MB/s - {:.1f}MB,共 {:.1f}MB,还剩 {:.0f} 秒 '.format(*print_params), end='')
f.close()
print('\r下载成功'+' '*50)
download('qq.zip')
用这个函数下载文件,有的文件会因为读不到content-length,报错
file_size = int(res.headers['Content-Length'])
File "F:\ProgramData\Anaconda3\lib\site-packages\requests\structures.py", line 54, in __getitem__
return self._store[key.lower()][1]
KeyError: 'content-length'
但文件是存在并可以下载的
有没有办法解决如果读取失败仍然下载并且能够显示下载进度或者速度随便一项,不然黑乎乎的等的心理很焦急的感觉
谢谢各位大神 |