How to download an image from a URL in Python

In this article, we will see how to download an image from a URL using Python. We will do this without making use of any browser. Let’s use the urllib module of Python for this purpose.

The urllib module comes inbuilt with Python and hence you need not install anything additionally.

Downloading an image from a URL in Python

We need to import the request module of the urllib library. The request module has several features that allow us to request data from URLs without actually opening them in the browser.

In order to download an image from a URL, we first need to specify the exact URL of the image and not that of the website.

Let’s look at the code now.

import urllib.request

# The URL of the image to be downloaded
link = "https://www.google.com/url?sa=i&source=images&cd=&ved=2ahUKEwibjMjKv5znAhWPxDgGHY3mDMQQjRx6BAgBEAQ&url=https%3A%2F%2Fwww.linkedin.com%2Fcompany%2Fcodespeedy&psig=AOvVaw2ltxjxyXDcIN4vtBa5R_Rt&ust=1579964231955182"

# The name of the new file
filename = "image1.jpg"

urllib.request.urlretrieve(link, filename)

Let’s go through the few lines of code line by line, firstly we need to import the urllib.request module. Next, we need to specify the URL of the image as a link. Then, the filename of the image that is being saved. Then the urlretrieve method is called with the link and filename as parameters.

When this code is executed, the image is fetched from the URL without actually opening the browser and is downloaded with the specified filename. The downloaded image is saved in the same directory as the current Python file. Multiple URLs can be specified as a list and the images can be downloaded one by one through a loop.

I hope you found this article helpful in solving your problem of downloading an image from a URL.

See also:

Leave a Reply

Your email address will not be published.