首页 > 解决方案 > 使用 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(

我在这里缺少哪些步骤?在此先感谢您的帮助。

标签: pythonweb-scrapingdownloadpython-requestszip

解决方案


我通过/在 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)

在这里查看它的实际应用。


推荐阅读