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.
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.
Get request is used to retrieve data from the server. To make a get request, we use:
Download files from URL in Python
Problem statement: Write a python program to download a file using URL.
- Import the requests module.
- Paste the URL of the file.
- Use the get method to retrieve the data from the URL pasted.
- Give the name and format of your choice to the file and open it in the write mode.
- Write the entire contents of the file to successfully save it.
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
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: