Ready to Start Your Career?

By: rk
January 23, 2017
Download an Image Using Python

By: rk
January 23, 2017
Estimated reading time: 1 minuteHello, everyone.Today I will show you how to use Python to download any image from the web.First, let's take a look at a script that I will explain what each statement is doing.
import urllib.requestimport randomdef downloader(image_url): file_name = random.randrange(1,10000) full_file_name = str(file_name) + '.jpg' urllib.request.urlretrieve(image_url,full_file_name)downloader(url)
We imported urllib.request and random module.The urllib.request module will help us to make a request with a URL. A random module has a function that will help us to generate a random number. So, our downloader function will take an image url. We have generated a random number between 1 and 1000 that we will store in a file_name variable.A file_name is an int so we have to change to a string using an str function. Next, we will add an image extension at the end of this and will store in a variable full_file_name. The urllib.request.urlretrieve function will take two arguments in an image_url from where it will download the image and file_name to store the image.Now we will pass a URL to a downloader function.Hope it helps newbies to Python.Thank you.