Easily Download Files from Web using Python

python programs

Using Python language (Python3.+) we can easily download files from the web over HTTP. Well, it is not the preferred method to download files but still let’s try this for fun.

Using urllib.request

Python comes with an inbuilt urllib module which we can use to download files from the web.

All we need is to pass the URL to the request.urlretreive() method of the urllib module.

The syntax for the request.urlretreive() is

request.urlretreive(url, filename)

The second parameter filename is optional.

Let’s try downloading the image using the same.

Downloading File using python urllib

No error means the file download is successful.

The file is saved in your current working directory of the python shell. To know your CWD use getcwd() method of os module.

current working directory in Python

Now we know where our file so let’s check.

File saved succesfully

Hooray, now let’s try another method.

Using wget

The wget is a 3rd party library solely meant for downloading files. Therefore we first need to install the module into our system using

pip install wget

Now we can use download() method of the module to download the file from the given URL.

The general syntax for the download method is:

wget.download(url, bar=bar_thermometer)

Again the second parameter is optional.

So the following program downloads files using wget module’s download method.

import wget

I recommend you to try this by yourself and comment below your result. I will be more than happy to help you out.

Leave a Reply

Your email address will not be published. Required fields are marked *