2017-06-19 39 views
-2

我需要使用url下载文件 - >https://readthedocs.org/projects/django/downloads/pdf/latest/如何使用重定向url下载文件?

此URL重定向到一个.pdf文件的URL。

我该如何使用python下载这个带有这个URL的文件?

我已经试过: -

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/') 

,但是这是不工作

+2

你有什么试过,没有奏效?不意味着要苛刻,但它是如此微不足道,我不明白你的实际问题是... –

+0

我试过的措施下载一个普通的.pdf扩展名的文件在URL中 – Nitanshu

回答

2
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) 

如果您想下载其他方法文件或者您只想获得最终重定向的网址,您可以使用requests.head(),如下所示:

r = requests.head(url, allow_redirects=True) # to get only final redirect url 
0

这将工作:

>>> import urllib 
>>> urllib.urlretrieve('https://readthedocs.org/projects/django/downloads/pdf/latest/', 'filename.pdf')