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

发布于 2021-02-02 23:22:20

我正在尝试使用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吗?

关注者
0
被浏览
129
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    你可以使用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不先将整个图像下载到内存中。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看