To download and save an image from the web using python's requests module.

Here is the code for urllib2

import urllib2
img = urllib2.urlopen("http://www.google.com/images/errors/robot.png")
with open(path, 'w') as f:
    f.write(img.read())

In requests we can either use the `response.raw file object <http://docs.python-requests.org/en/latest/api/#requests.Response.raw>`__, or iterate over the response.

Using response.raw way

import requests
import shutil

r = requests.get("http://www.google.com/images/errors/robot.png", 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:

import requests

r = requests.get("http://www.google.com/images/errors/robot.png", stream=True)
if r.status_code == 200:
    with open(path, 'wb') as f:
        for chunk in r:
            f.write(chunk)

We open the destination file as binary mode to avoid python translate newlines. We also set stream=True so that requests doesn't download the whole image into memory first.

SHARE
Next article How to install 7zip in ubuntu