How to Download an Image Using Python | by Chaitanya Baweja | Towards Data Science

Recently, I was working with a remote system and needed to download some images that my code will eventually process.
I could have used curl or wget on my terminal for downloading files. But, I wanted the entire process to be automated for the end-user.
This led me to the question:
How can I download an Image using Python?
In this tutorial, I will cover several modules that can be used for downloading files in Python(specifically images). The modules covered are: requests, wget, and urllib.
Disclaimer: Do not download or use any image that violates its copyright terms.
Code used in this tutorial was tested on an Ubuntu system with Python 3.6.9 installed.
I would highly recommend setting up a virtual environment with all the required libraries for testing. Here is how you can do it.
$ virtualenv image_download$ source ./image_download/bin/activate$ pip3 install requests wget
The image that we will use in the tutorial is located here. It is Free for Commercial Use and doesn’t require any attribution.
The Image URL that we will use for downloading will be:
https://cdn.pixabay.com/photo/2020/02/06/09/39/summer-4823612_960_720.jpg
We’re going to create a short script to download an image from a given URL.
The script will download the image adjacent to the script file and optionally, preserve the original file name.
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.
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 webimport shutil # to save it locallyimage_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.
Apart from the python requests module, we can also use the python wget module for downloading.
This is the python equivalent of GNU wget.
It’s quite straightforward to use.
The standard Python library for accessing websites via your program is urllib. It is also used by the requests module.
Through urllib, we can do a variety of things: access websites, download data, parse data, send GET and, POST requests.
We can download our image using just a few lines of code:
We used the urlretrieve method to copy the required web resource to a local file.
It is important to note that on some systems and a lot of websites, the above code will result in an error: HTTPError: HTTP Error 403: Forbidden.
This is because a lot of websites don’t appreciate random programs accessing their data. Some programs can attack the server by sending a large number of requests. This prevents the server from functioning.
This is why these websites can either:
Block you and you will receive HTTP Error 403.Send you different or NULL data.
Block you and you will receive HTTP Error 403.
Send you different or NULL data.
We can overcome this by modifying user-agent, a variable sent with our request. This variable, by default, tells the website that the visitor is a python program.
By modifying this variable, we can act as if the website is being accessed on a standard web browser by a normal user.
You can read more about it here.
Requests has become the de-facto way of downloading things in Python.
Even the urllib documentation page recommends Requests for a higher-level HTTP client interface.
If you want to have fewer dependencies in your program, you should go for urllib. It is a part of the standard libraries. So, there is no need to download it.
Hope you found this tutorial useful.
StackOverflow — Downloading Images via Urllib and RequestsRequests Librarywget libraryurllib library
StackOverflow — Downloading Images via Urllib and Requests