Open In App

How to Download Files from Urls With Python

Last Updated : 04 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Here, we have a task to download files from URLs with Python. In this article, we will see how to download files from URLs using some generally used methods in Python.

Download Files from URLs with Python

Below are the methods to Download files from URLs with Python:

Download Files From URLs Using ‘requests’ Module

In this example, below Python code utilizes the `requests` library to download a PDF file from a specified URL (`’https://media.geeksforgeeks.org/wp-content/uploads/20240226121023/GFG.pdf’`). It checks the HTTP response status code, and if it’s 200 (OK), the content is saved to a local file named ‘research_Paper_1.pdf’.

Python3




import requests
 
 
response = requests.get(url)
file_Path = 'research_Paper_1.pdf'
 
if response.status_code == 200:
    with open(file_Path, 'wb') as file:
        file.write(response.content)
    print('File downloaded successfully')
else:
    print('Failed to download file')


Output:

File downloaded successfully

Download Files From Urls Using ‘urllib3’ module:

In this example, below Python code uses the `urllib.request` module to download a PDF file from the specified URL (`’https://media.geeksforgeeks.org/wp-content/uploads/20240226121023/GFG.pdf’`). The `urlretrieve` function saves the content to a local file named ‘research_Paper_2.pdf’.

Python3




import urllib.request
 
 
file_Path = 'research_Paper_2.pdf'
urllib.request.urlretrieve(url, file_Path)


Output:

('research_Paper_2.pdf', <http.client.HTTPMessage at 0x7e5a2d16dcc0>)

Download Files From Urls Using ‘wget’ Module

In this example, below Python code utilizes the `wget` module to download a PDF file from the specified URL (`’https://media.geeksforgeeks.org/wp-content/uploads/20240226121023/GFG.pdf’`). The `wget.download` function saves the content to a local file named ‘research_Paper_3.pdf’.

Python3




import wget
 
 
file_Path = 'research_Paper_3.pdf'
wget.download(url, file_Path)
print('downloaded')


Output:

downloaded

Conclusion

In conclusion, Python provides multiple convenient methods for downloading files from URLs, catering to a range of preferences and project requirements. Whether using the straightforward urllib.request, the versatile requests library, or specialized modules like wget and urllib3, developers have the flexibility to choose an approach that best suits their needs. Armed with these techniques, efficiently incorporating file downloads into Python applications becomes a seamless and accessible task.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads