如何使用请求下载图像

2024-04-25 00:34:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用python的requests模块从web下载并保存图像。

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

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中使用响应的哪个属性吗?


Tags: 模块path代码formaturlimgreaddata
3条回答

这个怎么样,一个快速的解决方案。

import requests

url = "http://craphound.com/images/1006884_2adf8fc7.jpg"
response = requests.get(url)
if response.status_code == 200:
    with open("/Users/apple/Desktop/sample.jpg", 'wb') as f:
        f.write(response.content)

您可以使用^{} file object,也可以对响应进行迭代。

默认情况下,使用response.raw类文件对象不会解码压缩响应(使用GZIP或deflate)。通过将decode_content属性设置为Truerequests将其设置为False以控制解码本身),您可以强制它为您解压缩。然后,可以使用^{}让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字节块中的数据;如果您觉得另一个块大小更好,请使用具有自定义块大小的^{} method

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

从请求中获取类似文件的对象并将其复制到文件中。这样也可以避免一次把整件事都读入记忆。

import shutil

import requests

url = 'http://example.com/img.png'
response = requests.get(url, stream=True)
with open('img.png', 'wb') as out_file:
    shutil.copyfileobj(response.raw, out_file)
del response

相关问题 更多 >