You need to enable JavaScript to run this app. Python 3.7使用requests下载zip文件时获取到重定向HTML的问题咨询
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.7使用requests下载zip文件时获取到重定向HTML的问题咨询

问题原因定位
  • 目标URL返回的不是HTTP 3xx标准重定向,而是前端跳转的HTML页面:requests仅自动解析HTTP状态码类重定向,不会识别HTML内的meta跳转、JS跳转逻辑,因此直接保存了跳转页源码而非压缩包。
  • 缺少合法请求头:目标服务器存在基础反爬规则,未携带浏览器身份标识时会直接返回引导页,不触发资源下发逻辑。
可运行实现方案(适配Python 3.7)

依赖说明

仅使用已安装的requests搭配Python标准库完成,无需额外安装第三方依赖:

  • 用urllib.parse.urljoin将HTML内的相对路径转为合法绝对下载地址
  • 用正则表达式提取跳转逻辑中的真实资源地址
  • 流式分块写入文件,避免大文件占用过高内存

完整代码

import requests
import re
from urllib.parse import urljoin

# 模拟浏览器请求头,绕过基础反爬校验
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "Referer": "http://servicos.ibama.gov.br/ctf/publico/areasembargadas/",
}
initial_url = "http://servicos.ibama.gov.br/ctf/publico/areasembargadas/downloadListaAreasEmbargadas.php"

# 首次请求获取响应内容
resp = requests.get(initial_url, headers=headers, timeout=10)
resp.raise_for_status()  # 请求失败直接抛出异常,终止无效流程

# 若直接返回压缩包则直接保存
if "application/zip" in resp.headers.get("Content-Type", ""):
    with open("test.zip", "wb") as f:
        f.write(resp.content)
else:
    # 解析HTML内的两类常见跳转地址
    # 匹配meta刷新跳转格式:<meta http-equiv="refresh" content="0;url=xxx">
    meta_jump = re.search(r'content=["\']0;url=(.+?)["\']', resp.text)
    # 匹配普通下载链接格式:<a href="xxx.zip">
    download_link = re.search(r'href=["\'](.+?\.zip)["\']', resp.text)

    # 提取真实路径并拼接为绝对地址
    raw_path = meta_jump.group(1) if meta_jump else download_link.group(1)
    real_download_url = urljoin(initial_url, raw_path)

    # 流式下载压缩包,避免大文件占满内存
    with requests.get(real_download_url, headers=headers, stream=True, timeout=30) as zip_resp:
        zip_resp.raise_for_status()
        with open("test.zip", "wb") as f:
            # 按1MB分块写入
            for chunk in zip_resp.iter_content(chunk_size=1024 * 1024):
                if chunk:
                    f.write(chunk)

验证与调试方法

  • 下载完成后可直接用解压工具打开test.zip,或运行命令校验完整性:unzip -t test.zip(Linux/macOS环境)
  • 若正则匹配不到真实地址,可打印resp.text查看HTML结构,调整对应匹配规则即可。

内容的提问来源于stack exchange,提问作者user14699735

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.16 14:36:02