使用 Python 请求库保存一个大文件

可能的复制品:
如何使用请求 下载图像

我知道获取 URL 和 requests.get一样简单,我可以获取原始响应主体并将其保存到文件中,但是对于大文件,有没有直接流到文件的方法?比如我用它下载电影什么的?

103266 次浏览

Oddly enough, requests doesn't have anything simple for this. You'll have to iterate over the response and write those chunks to a file:

response = requests.get('http://www.example.com/image.jpg', stream=True)


# Throw an error for bad status codes
response.raise_for_status()


with open('output.jpg', 'wb') as handle:
for block in response.iter_content(1024):
handle.write(block)

I usually just use urllib.urlretrieve(). It works, but if you need to use a session or some sort of authentication, the above code works as well.