Welcome folks today in this blog post we will be downloading images
from url using request,wget and urllib
libraries. All the full source code of the application is shown below.
Get Started
In order to get started you need to install the below libraries
using the below command as shown below
pip install requests
pip install wget
pip install urllib3
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
## Importing Necessary Modules import requests # to get image from the web import shutil # to save it locally ## Set up the image URL and filename image_url = "https://codingdiksha.com/wp-content/uploads/2021/06/convert-json-to-excel-python.png" filename = image_url.split("/")[-1] # Open the url image, set stream to True, this will return the stream content. r = requests.get(image_url, stream = True) # Check if the image was retrieved successfully if r.status_code == 200: # Set decode_content value to True, otherwise the downloaded image file's size will be zero. r.raw.decode_content = True # Open a local file with wb ( write binary ) permission. with open(filename,'wb') as f: shutil.copyfileobj(r.raw, f) print('Image sucessfully Downloaded: ',filename) else: print('Image Couldn\'t be retreived') |
As you can see we have provided the url
for the image and then we are downloading it inside the local disk
using the python code. Here we are importing the requests
and the shutil
library. And here first of all we are making the http
requests to download the image
file using the get()
method. And then we are opening the image
file using the open()
method of the shutil
library.
Downloading Image From URL Using Wget Library
app.py
1 2 3 4 5 6 7 8 9 10 |
# First import wget python module. import wget # Set up the image URL image_url = "https://codingdiksha.com/wp-content/uploads/2021/06/convert-json-to-excel-python.png" # Use wget download method to download specified image url. image_filename = wget.download(image_url) print('Image Successfully Downloaded: ', image_filename) |
As you can see we are importing the wget
library and then we are having the image url
and then we are using the download()
method to actually fetch the image and saving
the image inside the local disk.
Downloading Image From URL Using Urllib Library
app.py
1 2 3 4 5 6 7 8 9 |
# importing required modules import urllib.request # setting filename and image URL filename = 'codingdiksha.jpg' image_url = "https://codingdiksha.com/wp-content/uploads/2021/06/convert-json-to-excel-python.png" # calling urlretrieve function to get resource urllib.request.urlretrieve(image_url, filename) |
As you can see we are importing the urllib
module at the top and then we are providing the custom
file name and the url
of the image file and then we are using the urlretrieve()
method to download the image
and saving it inside the local disk.