Downloading an image using urllib.request library

Firstly the relevant libraries are imported. Then a call to the web address is made, and the resource returned in the response is stored in the file named w3wiki.png. It should be noted that the extension of the image file has to be known here, i.e., the container for the image file format, such as png, jpg, SVG, BMP, etc., needs to be known beforehand. In this case, the image was in PNG format, which was mentioned in the output file name. After the aforementioned function has been executed successfully, a file named w3wiki.png will be produced in the current working directory of the program. This file is later opened using the Image.open function and, in the end, displayed using the Image.show function.

Python3




import urllib.request
from PIL import Image
  
# Retrieving the resource located at the URL
# and storing it in the file name a.png
url = "https://media.w3wiki.org/\
wp-content/uploads/20210224040124/\
JSBinCollaborativeJavaScriptDebugging6-300x160.png"
urllib.request.urlretrieve(url, "w3wiki.png")
  
# Opening the image and displaying it (to confirm its presence)
img = Image.open(r"w3wiki.png")
img.show()


Output:

 

How to download an image from a URL in Python

Downloading content from its URL is a common task that Web Scrapers or online trackers perform. These URLs or Uniform Resource Locators can contain the web address (or local address) of a webpage, website, image, text document, container files, and many other online resources. It is quite easy to download and store content from files on the internet. This article will teach you how to download an image from a URL in Python.

Later, we would be using the pillow library to display the downloaded image (to confirm its presence). Which could be installed into the Python distribution using:

!pip install requests
!pip install pillow

* The process of displaying the image is optional and does not add anything to the problem at hand other than the clarity of results it produces

Similar Reads

Downloading an image using urllib.request library

Firstly the relevant libraries are imported. Then a call to the web address is made, and the resource returned in the response is stored in the file named geeksforgeeks.png. It should be noted that the extension of the image file has to be known here, i.e., the container for the image file format, such as png, jpg, SVG, BMP, etc., needs to be known beforehand. In this case, the image was in PNG format, which was mentioned in the output file name. After the aforementioned function has been executed successfully, a file named geeksforgeeks.png will be produced in the current working directory of the program. This file is later opened using the Image.open function and, in the end, displayed using the Image.show function....

Downloading an image using the requests library

...