Questions/How to download a pdf in python from url using just requests?
·
•••Report content

How to download a pdf in python from url using just requests?

PythonRequestsPdfDownloadWeb ScrapingFile Handling
Idyllic answer2024-06-05

To download a PDF from a URL using Python with the requests library, you can follow these steps:

```

import requests

url = 'http://www.hrecos.org//images/Data/forweb/HRTVBSH.Metadata.pdf'

r = requests.get(url, stream=True)

with open('/tmp/metadata.pdf', 'wb') as fd:

for chunk in r.iter_content(chunk_size=1024):

fd.write(chunk)

```

This code sends a GET request to the specified URL and downloads the PDF file in chunks. The `stream=True` parameter allows the file to be downloaded in chunks, which is more memory-efficient for large files. The `iter_content` method is used to iterate over the chunks of the file, and the `fd.write` method is used to write each chunk to the file.

Make sure to replace the `url` variable with the URL of the PDF file you want to download. Also, replace the `/tmp/metadata.pdf` path with the desired file path and name for the downloaded PDF file.

Note: The `chunk_size` parameter in the `iter_content` method specifies the size of each chunk in bytes. You can adjust this value depending on your specific needs.

Sources

YOUR CREATION. YOUR CHOICE.

Made by you.
Seen by who?

Before you create, choose who gets to see it.

Generation visibility
18+ only

Show mature content?

Mature mode shows adults who turn it on tasteful 18+ creations.