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 = ""

# 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. Required fields are marked *