Categories
Python

How to download an Image using Python Requests Module 

Requests is a neat and user-friendly HTTP library in Python. It makes sending HTTP/1.1 requests extremely straightforward.

It seems to be the most stable and recommended method for downloading any type of file using Python.

Here is the entire code.

## Importing Necessary Modules
import requests # to get image from the web
import shutil # to save it locally

## Set up the image URL and filename
image_url = "https://cdn.pixabay.com/photo/2020/02/06/09/39/summer-4823612_960_720.jpg"
filename = image_url.split("/")[-1]

# Open the url image, set stream to True, this will return the stream content.
r = requests.get(image_url, stream = True)

# Check if the image was retrieved successfully
if r.status_code == 200:
    # Set decode_content value to True, otherwise the downloaded image file's size will be zero.
    r.raw.decode_content = True
    
    # Open a local file with wb ( write binary ) permission.
    with open(filename,'wb') as f:
        shutil.copyfileobj(r.raw, f)
        
    print('Image sucessfully Downloaded: ',filename)
else:
    print('Image Couldn\'t be retreived')

Don’t Worry. Let’s break it down line-by-line.

We will start by importing the necessary modules and will also set the Image URL.

import requests # to get image from the web
import shutil # to save it locally
image_url = "https://cdn.pixabay.com/photo/2020/02/06/09/39/summer-4823612_960_720.jpg"

We use slice notation to separate the filename from the image link. We split the Image URL using forward-slash( /) and then use [-1] to slice the last segment.

filename = image_url.split("/")[-1]

The get() method from the requests module will be used to retrieve the image.

r = requests.get(image_url, stream = True)

Use stream = True to guarantee no interruptions.

Now, we will create the file locally in binary-write mode and use the copyfileobj() method to write our image to the file.

# Set decode_content value to True, otherwise the downloaded image file's size will be zero.
r.raw.decode_content = True
# Open a local file with wb ( write binary ) permission.
with open(filename,'wb') as f:
        shutil.copyfileobj(r.raw, f)

We can also add certain conditionals to check if the image was retrieved successfully using Request’s Status Code.

We can also improve further by adding progress bars while downloading large files or a large number of files. Here is a good example.

Requests is the most stable and recommended method for downloading any type of file using Python.

Source

Leave a Reply

Your email address will not be published. Required fields are marked *