When attempting to download an image from the internet using Python's requests module, you may encounter issues with the code compared to using urllib2's urlopen method. This article addresses these challenges and provides solutions.
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)
The issue arises when using requests because the attribute from the response that contains the image data is different from that of urlopen in urllib2.
To retrieve the image data from the requests response, there are two options:
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)
By setting stream=True in the requests call, it prevents downloading the entire image into memory at once. The file should be opened in binary mode to avoid errors.
The above is the detailed content of How to Properly Download Images Using Python's `requests` Module?. For more information, please follow other related articles on the PHP Chinese website!