我正在尝试使用 python 的 requests
模块从网络下载并保存图像。
这是我使用的(工作)代码:
img = urllib2.urlopen(settings.STATICMAP_URL.format(**data))
with open(path, 'w') as f:
f.write(img.read())
这是使用 requests
的新(非工作)代码:
r = requests.get(settings.STATICMAP_URL.format(**data))
if r.status_code == 200:
img = r.raw.read()
with open(path, 'w') as f:
f.write(img)
你能帮我从 requests
的响应中使用什么属性吗?
原文由 shkschneider 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以使用
response.raw
文件对象,或者遍历响应。要使用
response.raw
类文件对象,默认情况下不会解码压缩响应(使用 GZIP 或 deflate)。 You can force it to decompress for you anyway by setting thedecode_content
attribute toTrue
(requests
sets it toFalse
to control decoding itself )。然后,您可以使用shutil.copyfileobj()
让 Python 将数据流式传输到文件对象:要迭代响应,请使用循环;像这样迭代可确保在此阶段解压缩数据:
这将以 128 字节块的形式读取数据;如果您觉得另一个块大小效果更好,请使用带有自定义块大小的
Response.iter_content()
方法:请注意,您需要以二进制模式打开目标文件,以确保 python 不会尝试为您翻译换行符。我们还设置了
stream=True
这样requests
不会先将整个图像下载到内存中。