Download an Image Using Python

January 23, 2017 | Views: 33764

Begin Learning Cyber Security for FREE Now!

FREE REGISTRATIONAlready a Member Login Here

Estimated reading time: 1 minute

Hello, 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.request
import random


def 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.

Share with Friends
FacebookTwitterLinkedInEmail
Use Cybytes and
Tip the Author!
Join
Share with Friends
FacebookTwitterLinkedInEmail
Ready to share your knowledge and expertise?
4 Comments
  1. Thanks 😉

  2. > wget https://www.cybrary.it/wp-content/uploads/avatars/48467/5882da5be53fc-bpfull.jpg

    In which way this python script is better than the previous line?

    • With the python script you could configure to do more advance task like dynamically pull an image based on a variable such as a date or name, or use it along side an API etc. This is just an example of calling the function of the given library, its not really about the sole task of downloading a file.

Comment on This

You must be logged in to post a comment.

Our Revolution

We believe Cyber Security training should be free, for everyone, FOREVER. Everyone, everywhere, deserves the OPPORTUNITY to learn, begin and grow a career in this fascinating field. Therefore, Cybrary is a free community where people, companies and training come together to give everyone the ability to collaborate in an open source way that is revolutionizing the cyber security educational experience.

Support Cybrary

Donate Here to Get This Month's Donor Badge

 

We recommend always using caution when following any link

Are you sure you want to continue?

Continue
Cancel