通常,我们都会用 requests 库去下载,这个库用起来太方便了。
使用以下流式代码,无论下载文件的大小如何,Python 内存占用都不会增加:
iter_content[1] 函数本身也可以解码,只需要传入参数 decode_unicode = True 即可。另外,搜索公众号顶级Python后台回复“进阶”,获取一份惊喜礼包。请注意,使用 iter_content 返回的字节数并不完全是 chunk_size,它是一个通常更大的随机数,并且预计在每次迭代中都会有所不同。方法二使用 Response.raw[2] 和 shutil.copyfileobj[3]response.raw.read = functools.partial(response.raw.read, decode_content=True)
方法二更快。方法一如果 2-3 MB/s 的话,方法二可以达到近 40 MB/s。
[1]iter_content: https://requests.readthedocs.io/en/latest/api/#requests.Response.iter_content
[2]Response.raw: https://requests.readthedocs.io/en/latest/api/#requests.Response.raw
[3]shutil.copyfileobj: https://docs.python.org/3/library/shutil.html#shutil.copyfileobj