How to download files from URL using python?

In this tutorial, we will learn how to download files from URL using python. Before getting on to the actual code, let us see some prerequisites for the same.

Requests module

As we are aware that making even a simple HTTP request involves writing lots of code. Requests basically allow us to make all kinds of HTTP/1.1  request by just importing it. Hence, it is much more efficient.

Click here for detailed documentation on requests.

To get started with requests, install it in your software or download it using:

pip install requests

Or download it from here. Next, import it in your code using the keyword import.

import requests

Get request

Get request is used to retrieve data from the server. To make a get request, we use:

requests.get()

Download files from URL in Python

Problem statement: Write a python program to download a file using URL.

Steps/Algorithm:

  1. Import the requests module.
  2. Paste the URL of the file.
  3. Use the get method to retrieve the data from the URL pasted.
  4. Give the name and format of your choice to the file and open it in the write mode.
  5. Write the entire contents of the file to successfully save it.

Program/Code:

import requests

url = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"
#just a random link of a dummy file

r = requests.get(url)
#retrieving data from the URL using get method

with open("dummy.pdf", 'wb') as f:
#giving a name and saving it in any required format
#opening the file in write mode

    f.write(r.content) 
#writes the URL contents from the server

Output:

The required file from the URL will automatically get downloaded and saved in the same folder in which code was written.

You may also read:

Leave a Reply

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