Python 3 Download Images From URL using Request,Wget & UrlLib Libraries Full Example 2020

Python 3 Download Images From URL using Request,Wget & UrlLib Libraries Full Example 2020

 

 

 

 

 

 

 

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

 

 

 

## 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')

 

READ  Python 3 Tkinter Web Scraping Script to Build a Realtime International Currency Converter Foreign Exchange (All Currencies Supported) GUI Desktop App Full Project For Beginners

 

 

Downloading Image Using Wget

 

 

# 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)

 

READ  Python Tkinter Multiple Choice Quiz Game Using Pillow Library GUI Desktop App Full Project With Source Code For Beginners

 

 

Downloading Image Using UrlLib

 

 

 

# 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)

 

 

 

Leave a Reply