python requests下载图片_Python: 使用requests下载图片

来自最佳答案(推荐下面第一个):

You can either use the response.raw file object, or iterate over the response.

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)

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)

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值