且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-10-21 13:57:28

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() 如下所示:

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