Skip to main content
 首页 » 编程设计

python之如何从重定向的 URL 下载文件

2025年05月04日16shihaiming

我需要使用 url 下载文件 --> https://readthedocs.org/projects/django/downloads/pdf/latest/

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

但这行不通

请您参考如下方法:

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) 

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

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