我试图使用python的请求模块从网络下载并保存一张图像。
下面是我使用的(工作)代码:
img = urllib2.urlopen(settings.STATICMAP_URL.format(**data))
with open(path, 'w') as f:
f.write(img.read())
下面是使用请求的新(无效)代码:
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)
你能帮我从请求中使用响应的什么属性吗?
这可能比使用请求更容易。这是我唯一一次建议不要使用请求来做HTTP的事情。
使用urllib的两个内衬:
>>> import urllib
>>> urllib.request.urlretrieve("http://www.example.com/songs/mp3.mp3", "mp3.mp3")
还有一个叫做wget的Python模块,它非常容易使用。在这里找到。
这说明了设计的简单性:
>>> import wget
>>> url = 'http://www.futurecrew.com/skaven/song_files/mp3/razorback.mp3'
>>> filename = wget.download(url)
100% [................................................] 3841532 / 3841532>
>> filename
'razorback.mp3'
享受。
编辑:您还可以添加一个out参数来指定路径。
>>> out_filepath = <output_filepath>
>>> filename = wget.download(url, out=out_filepath)