How to Download an Image from a URL in Python?

In this post, we’ll look at how to use Python to download an image from a URL. This will be done without the need for a browser. Let’s utilize Python’s urllib module to accomplish this.

The urllib module is inbuilt into Python, so you don’t need to install anything extra.

urllib module:

The Urllib package is Python’s URL handling module. It is used to retrieve URLs (Uniform Resource Locators). It employs the urlopen function and can retrieve URLs using a variety of protocols.

Urllib is a package that contains numerous URL-related modules, such as:

  • urllib.request is used to open and read URLs, whereas urllib.parse is used to parse URLs.
  • urllib.error for the exceptions that were thrown
  • urllib.robotparser is used to parse robot.txt files.

Download an Image from a URL in Python

Approach:

  • Import request function from urllib module using the import keyword.
  • Give some random url(link) from the browser and store it in a variable
  • Give some random file name to the image for saving it and store it in another variable
  • Pass the above given url, image filename as arguments to the urlretrieve() function to download the image from url and save it with the given file name.
  • The Exit of the Program.

Below is the implementation:

# Import request function from urllib module using the import keyword.
import urllib.request
# Give some random url(link) from the browser and store it in a variable
gvn_url = "https://btechgeeks.com/wp-content/uploads/2020/11/cropped-BTechGeeks.png"
# Give some random file name to the image for saving it and store it in another variable
Imagefile_name = "sampleimage.jpg" 
# Pass the above given url, image filename as arguments to the urlretrieve() function  
# to download the image from url and save it with the given file name.
urllib.request.urlretrieve(gvn_url, Imagefile_name)

Output:

('sampleimage.jpg', <http.client.HTTPMessage at 0x7f3ff50cfdd0>)

sampleimage.jpg:

Image from url

Explanation:

When you run this code, the image is retrieved from the URL without opening the browser and saved with the filename you choose. The image is downloaded and saved in the same directory as the Python programm that is now running. A list of URLs can be provided, and photos can be downloaded one at a time using a loop.