我正尝试使用Python的requests库下载文件。在Python 2.7中可以工作,但现在不行了。我非常困惑,一定有更简单的答案。由于文件可能相当大,我真的希望能有一个进度条,因此我正在使用Python进度条来完成这项工作。
r = requests.get(file_url, data={'track': 'requests'})
size = int(r.headers['Content-Length'].strip())
self.bytes = 0
widgets = [name, ": ", Bar(marker="|", left="[", right=" "),
Percentage(), " ", FileTransferSpeed(), "] ",
self,
" of {0}MB".format(round(size / 1024 / 1024, 2))]
pbar = ProgressBar(widgets=widgets, maxval=size)
pbar.start()
file = b""
for chunk in r.iter_content()
if chunk:
file += chunk
self.bytes += 1
pbar.update(self.bytes)
我发现使用iter_content是获取连续更新的最佳方法。我尝试使用iter_lines,但它会弄乱文件。下载会突然停止且非常慢,即使下载了10%,也需要15分钟才能完成。同时,在字节模式下打开文件并写入内容是行不通的,它根本不会抛出错误。而当我尝试使用以下代码打印块所包含的内容时:
print(chunk.decode("utf-8")
工作正常,但只有少数字符。在某个时候它会抱怨
UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte
即使在iter_content中使用“decode_unicode=True”,也没有任何作用。我感到困惑,不知道该怎么办。使用Py3k不应该这么难。
requests.get(file_url, prefetch=False)
才能证明你的说法是正确的。否则,@antihero 是完全正确的。 - heycosmo