3

I need to download a file using url-->https://readthedocs.org/projects/django/downloads/pdf/latest/

This url redirects to a url with a .pdf file.

How can I download that file with this url using python ?

I've tried :-

import urllib
def download_file(download_url):
    web_file = urllib.urlopen(download_url)
    local_file = open('some_file.pdf', 'w')
    local_file.write(web_file.read())
    web_file.close()
    local_file.close()

if __name__ == 'main':
    download_file('https://readthedocs.org/projects/django/downloads/pdf/latest/')

but this is not working

2
  • 3
    What have you tried that didn't work ? Don't mean to be harsh but it's so trivial that I fail to understand what your actual problem is... Jun 19, 2017 at 11:42
  • I've tried the measures to download a regular file with .pdf extension in the URL
    – Nitanshu
    Jun 19, 2017 at 17:18

1 Answer 1

11
import requests
url = 'https://readthedocs.org/projects/django/downloads/pdf/latest/'
r = requests.get(url, allow_redirects=True)  # to get content after redirection
pdf_url = r.url # 'https://media.readthedocs.org/pdf/django/latest/django.pdf'
with open('file_name.pdf', 'wb') as f:
    f.write(r.content)

If you want to download the file from other method or you want to get only final redirected URL you can use requests.head() as shown below:

r = requests.head(url, allow_redirects=True)  # to get only final redirect url
1
  • @TheGodfather so as it is out of scope for requests module.
    – Gahan
    Aug 9, 2019 at 13:24

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.