You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Wget从直链下载PDF失败如何修复,有无Python替代解决方案?

问题原因

Read error (Unknown error) in headers报错本质是目标服务器做了反爬校验,拦截了wget默认标识的请求,通常是User-Agent、Referer等请求头不符合要求,或是TLS协议版本不兼容导致。

wget修复方案

核心是补充模拟浏览器的请求头,修改后的命令如下:

wget -A pdf -nc -np -nd --content-disposition --wait=1 --tries=5 --user-agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36" "https://prospektbestellung.nordseetourismus.de/mediafiles/Sonstiges/Ortsprospekte/amrum2021.pdf"

如果依然报错,可以尝试追加以下参数:

  • 增加--referer="https://prospektbestellung.nordseetourismus.de/"指定来源页
  • 增加--secure-protocol=TLSv1_2指定兼容的TLS协议版本
  • 非必要不推荐使用:增加--no-check-certificate忽略SSL证书校验
Python实现方案

基于requests库实现(推荐)

先安装依赖:
pip install requests
代码示例:

import requests

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36",
    "Referer": "https://prospektbestellung.nordseetourismus.de/"
}
pdf_url = "https://prospektbestellung.nordseetourismus.de/mediafiles/Sonstiges/Ortsprospekte/amrum2021.pdf"

try:
    resp = requests.get(pdf_url, headers=headers, stream=True, timeout=10)
    resp.raise_for_status()
    with open("amrum2021.pdf", "wb") as f:
        for chunk in resp.iter_content(chunk_size=8192):
            f.write(chunk)
    print("PDF下载完成")
except Exception as e:
    print(f"下载失败:{e}")

基于内置urllib实现(无第三方依赖)

不需要安装额外依赖,直接用Python自带标准库实现:

from urllib import request

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36",
    "Referer": "https://prospektbestellung.nordseetourismus.de/"
}
pdf_url = "https://prospektbestellung.nordseetourismus.de/mediafiles/Sonstiges/Ortsprospekte/amrum2021.pdf"

req = request.Request(pdf_url, headers=headers)
try:
    with request.urlopen(req, timeout=10) as resp, open("amrum2021.pdf", "wb") as f:
        f.write(resp.read())
    print("PDF下载完成")
except Exception as e:
    print(f"下载失败:{e}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 05:12:02