How to download images from internet using Python (with video)

Updated on Oct. 12, 2017 | 1640 |   python,

Python has super cool features that allow you to download and retrieve information from the internet. In this tutorial, we are going to learn about how to download an image from the internet using Python. You can learn from video or text tutorial. It's totally upto you :-). 


 

Step 1: We will first import necessary modules for our program. Here, we are importing random and urllib.request. The module, random, will allow us to generate random numbers which we will use to save the name of our image. The urllib.request module will allow us to request for a link over the internet. 

import random 

import urllib.request

 

Step 2: Now, we will create a function called download_image( url ), where url is the parameter which will take the image url as an input. 

      def download_image(url):

 

Step 3: To save the image in our own preferred name, we will randomly generate a number which will be between 100 and 500 and add an extension of png or jpg according to the respective image on internet. To generate the random number use random.randrange(first_param, second_paramfunction and convert the number into string using str() function and add an extension of jpg or png. Here, we have added png extension.

img_name = random.randrange(100500

full_name = str(img_name) + '.png'

 

Step 4 (Final): In this final step, you need to call urlretrieve() function of urllib.request module. This function takes upto 4 parameters url, filename, reporthook & data where url, the only parameter is the mandatory one and other threes are optional. For our program, we will use two parameters (url and filename). Url will be the link of the image on internet and filename will be the full_name which we have got into the step 4. In the end, call the download_image() function with the url parameter.

      urllib.request.urlretrieve(url,full_name)


download_image('http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg')

 

Full Source Code: 

import random 

import urllib.request


def download_image(url):

    img_name = random.randrange(100500

    full_name = str(img_name) + '.png'

    urllib.request.urlretrieve(url,full_name)


download_image('http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg')


 

Congratulations! You have downloaded an image from an internet for the first time. If you face any problem, comment into the comment section. Don’t forget to check our official website where you will have all amazing courses for free!

[The Image URL has been used for educational purpose only]