Downloading an image using the requests library
Downloading an image into python could also be performed by using the request library. The library is a part of the default python distribution.
Python3
import requests from PIL import Image url = 'https: / / media.w3wiki.org / \ wp - content / uploads / 20210224040124 / JSBinColla\ borativeJavaScriptDebugging6 - 300x160 .png' # This statement requests the resource at # the given link, extracts its contents # and saves it in a variable data = requests.get(url).content # Opening a new file named img with extension .jpg # This file would store the data of the image file f = open ( 'img.jpg' , 'wb' ) # Storing the image data inside the data variable to the file f.write(data) f.close() # Opening the saved image and displaying it img = Image. open ( 'img.jpg' ) img.show() |
Output:
Firstly, the relevant libraries were imported. Then a variable named URL is assigned the address from where the image file is to be downloaded. Then a request to the URL using the function requests.get is made. Then the contents from the response are extracted. A new file is opened named img.jpg (make sure the file extension is the same as the downloaded file). The data that was obtained by the get function is stored in this file. Later this file is opened via PIL and displayed.
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