Downloading Images in Python
In this video we have used namely three libraries for this task
request
: You can install this library by executing pip install request
wget
: You can install tis library by executing pip install wget
urllib
: You can install this library by executing pip install urllib
Downloading Image Using Request
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://codingshiksha.com/wp-content/uploads/2020/09/Screenshot_7-653x318.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') |
Downloading Image Using Wget
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://cdn.pixabay.com/photo/2020/02/06/09/39/summer-4823612_960_720.jpg" # Use wget download method to download specified image url. image_filename = wget.download(image_url) print('Image Successfully Downloaded: ', image_filename) |
Downloading Image Using UrlLib
1 2 3 4 5 6 7 8 9 |
# importing required modules import urllib.request # setting filename and image URL filename = 'sunshine_dog.jpg' image_url = "https://codingshiksha.com/wp-content/uploads/2020/09/Screenshot_7-653x318.png" # calling urlretrieve function to get resource urllib.request.urlretrieve(image_url, filename) |