How to Download the Files From Web Pages Using Python 3.X

by Mike Wallace

The Internet is a tremendous resource that continues to shape the modern era. As the Internet expands, the expectation for software to interface with the Internet also increases. Modern programming languages have built-in features that allow you to interact with online resources. For example, Python allows you to download files from websites with a few short lines of code. The method for downloading files is different in Python 3.x than in earlier versions of Python.

1

Open the text editor IDLE that comes with Python. A blank source code file opens in the IDLE editor.

2

Import the "urllib.request" module by writing the following line of code at the top of the source code file:

import urllib.request;

3

Declare a string that will hold the file location in URL format. For example, if you were downloading the file "http://www.python.org/images/python-logo.gif," you could declare the string like this:

URL = "http://www.python.org/images/python-logo.gif"

4

Declare a string that will hold the name of the file once it is downloaded onto your PC. You can name it whatever you want, but the extensions must be the same in order for the file to read correctly. To save the file to the directory your Python script is executed in, you could write this:

filename = "logo.gif"

5

Download the file by writing this single line of code:

urllib.request.urlretrieve(URL, filename)

6

Execute the program by pressing F5. The program has no output, so it will just execute and then close itself. However, in the folder where the script is located, the file "logo.gif" appears. It may take a moment for the download to complete.

Items you will need

About the Author

Mike Wallace began writing professionally in 2009. He is currently employed as a software engineer who designs, develops and tests software systems. He holds a Bachelor of Science in computer engineering and a Master of Science in electrical and computer engineering from California State University, Chico.