小编典典

Python-如何使用请求下载图像

python

我正在尝试使用pythonrequests模块从网络下载并保存图像。

这是我使用的(工作)代码:

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吗?


阅读 573

收藏
2020-02-11

共1个答案

小编典典

你可以使用response.rawfile对象,也可以遍历响应。

response.raw默认情况下,使用类似文件的对象不会解码压缩的响应(使用GZIP或deflate)。你可以通过将decode_content属性设置为True(requests将其设置False为控制自身解码)来强制为你解压缩。然后,你可以使用shutil.copyfileobj()Python将数据流式传输到文件对象:

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)    

要遍历响应,请使用循环;这样迭代可确保在此阶段解压缩数据:

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()方法:

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=Truerequests不先将整个图像下载到内存中。

2020-02-11