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.
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.
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_param) function 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(100, 500)
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.
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]