如何使用请求下载图像 [英] How to download image using requests
问题描述
我正在尝试使用 python 的 requests
模块从网络下载并保存图像.
I'm trying to download and save an image from the web using python's requests
module.
这是我使用的(工作)代码:
Here is the (working) code I used:
img = urllib2.urlopen(settings.STATICMAP_URL.format(**data))
with open(path, 'w') as f:
f.write(img.read())
这是使用 requests
的新(非工作)代码:
Here is the new (non-working) code using 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
使用响应中的什么属性吗?
Can you help me on what attribute from the response to use from requests
?
推荐答案
您可以使用 response.raw
文件对象,或迭代响应.
You can either use the response.raw
file object, or iterate over the response.
默认情况下,使用 response.raw
类文件对象不会解码压缩响应(使用 GZIP 或 deflate).您可以通过将 decode_content
属性设置为 True
(requests
将其设置为 False
控制解码本身).然后您可以使用 shutil.copyfileobj()
让 Python 将数据流式传输到文件对象:
To use the response.raw
file-like object will not, by default, decode compressed responses (with GZIP or deflate). You can force it to decompress for you anyway by setting the decode_content
attribute to True
(requests
sets it to False
to control decoding itself). You can then use shutil.copyfileobj()
to have Python stream the data to a file object:
import requests
import shutil
r = requests.get(settings.STATICMAP_URL.format(**data), stream=True)
if r.status_code == 200:
with open(path, 'wb') as f:
r.raw.decode_content = True
shutil.copyfileobj(r.raw, f)
要迭代响应,请使用循环;像这样迭代确保数据在这个阶段被解压:
To iterate over the response use a loop; iterating like this ensures that data is decompressed by this stage:
r = requests.get(settings.STATICMAP_URL.format(**data), stream=True)
if r.status_code == 200:
with open(path, 'wb') as f:
for chunk in r:
f.write(chunk)
这将读取 128 字节块中的数据;如果您觉得其他块大小效果更好,请使用 Response.具有自定义块大小的 iter_content()
方法:
This'll read the data in 128 byte chunks; if you feel another chunk size works better, use the Response.iter_content()
method with a custom chunk size:
r = requests.get(settings.STATICMAP_URL.format(**data), stream=True)
if r.status_code == 200:
with open(path, 'wb') as f:
for chunk in r.iter_content(1024):
f.write(chunk)
请注意,您需要以二进制模式打开目标文件,以确保 python 不会尝试为您翻译换行符.我们还设置了 stream=True
以便 requests
不会先将整个图像下载到内存中.
Note that you need to open the destination file in binary mode to ensure python doesn't try and translate newlines for you. We also set stream=True
so that requests
doesn't download the whole image into memory first.
这篇关于如何使用请求下载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!