如何从重定向的 URL 下载文件?
How to download a file from a URL which redirects?
我需要使用 url-->https://readthedocs.org/projects/django/downloads/pdf/latest/
下载文件
这个 url 重定向到一个 url 和一个 .pdf 文件。
如何使用 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
我需要使用 url-->https://readthedocs.org/projects/django/downloads/pdf/latest/
下载文件这个 url 重定向到一个 url 和一个 .pdf 文件。
如何使用 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