Nit*_*shu 1 python urllib2 python-3.x python-requests
我需要使用url下载文件-> https://readthedocs.org/projects/django/downloads/pdf/latest/
该URL重定向到带有.pdf文件的URL。
如何使用python使用该网址下载该文件?
我试过了 :-
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/')
Run Code Online (Sandbox Code Playgroud)
但这不起作用
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)
Run Code Online (Sandbox Code Playgroud)
如果要从其他方法下载文件,或者只想获取最终重定向的URL,则可以requests.head()如下所示使用:
r = requests.head(url, allow_redirects=True) # to get only final redirect url
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4623 次 |
| 最近记录: |