python - 使用 python 中的请求模块从 URL 下载 zip 文件
问题描述
当我访问这个网站时,我的浏览器会打开一个框来下载一个 zip 文件。
我正在尝试通过 python 脚本下载 zip 文件(我是编码的初学者)。我想在将来自动化下载一批类似链接的过程,但我现在只用一个链接进行测试。这是我的代码:
import requests
url = 'https://sigef.incra.gov.br/geo/exportar/vertice/shp/454698fd-6dfa-49a1-8096-bd9bb57b62ca'
r = requests.get(url, verify=False, allow_redirects=True)
open('verticeshp454698fd-6dfa-49a1-8096-bd9bb57b62ca.zip', 'wb').write(r.content)
作为输出,我得到一个损坏的 zip 文件,而不是我想要的。我还在命令提示符下收到以下消息:
C:\Users\joaop\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connectionpool.py:979: InsecureRequestWarning: Unverified HTTPS request is being made to host 'sigef.incra.gov.br'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
warnings.warn(
我在这里缺少哪些步骤?在此先感谢您的帮助。
解决方案
我通过/
在 url 的末尾添加它来工作
import requests
# the `/` at the end is important
url = 'https://sigef.incra.gov.br/geo/exportar/vertice/shp/454698fd-6dfa-49a1-8096-bd9bb57b62ca/'
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2866.71 Safari/537.36",
}
r = requests.get(url, headers=headers, verify=False, allow_redirects=True)
# get the filename from the headers `454698fd-6dfa-49a1-8096-bd9bb57b62ca_vertice.zip`
filename = r.headers['Content-Disposition'].split("filename=")[-1]
with open(filename, 'wb') as f:
f.write(r.content)
在这里查看它的实际应用。
推荐阅读
- python - 如何在python中打印十进制直到N?
- flutter - GridView 保留所有元素,而不是在屏幕上构建它们
- python - Tornado 将导入 Jupyter 而不是 VS Code
- authentication - NextJs/ Apollo Client/ NextAuth 问题将授权承载令牌正确设置为标头
- vue.js - nuxt.js nginx err_incomplete_chunked_encoding_200
- javascript - js根据输入数字计算总价并显示
- java - 如何通过调暗某些文件来自定义 Eclipse RCP 中的 c 透视图?
- c# - ASP.NET 无效的 base64 输入。输入不是有效的 Base-64 字符串
- firebase - Is it possible to destroy firestore listeners soon if client is not connected?
- git - Rebase-merge another branch into the current one