python requests file download

Python Requests File Download

If you're working with web scraping or web automation, chances are you'll need to download files from the internet using Python. Luckily, the requests module in Python makes it easy to download files with just a few lines of code.

Using the requests module

Here's an example of how to use the requests module to download a file:

import requests

url = ''
response = requests.get(url)

with open('file.pdf', 'wb') as f:

In this example, we first import the requests module. Then, we define the URL of the file we want to download. We make a GET request to that URL using requests.get(), which returns a Response object.

We then open a file in write binary mode using open() and write the binary content of the response to the file using f.write().

Using urllib

You can also use the urllib module in Python to download files:

import urllib.request

url = ''
urllib.request.urlretrieve(url, 'file.pdf')

In this example, we import the urllib.request module and define the URL of the file we want to download. We then use the urlretrieve() function to download the file and save it to disk.

Using wget

If you have wget installed on your system, you can also use it to download files:

import os

url = ''
os.system('wget {}'.format(url))

In this example, we first import the os module. We define the URL of the file we want to download and use the os.system() function to execute the wget command.

These are just a few examples of how you can download files using Python. Each method has its pros and cons, so choose the one that works best for your specific use case.