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

使用Python requests模块下载PDF遇403错误求助

解决requests请求PDF返回403的问题

问题原因

服务器返回403是因为它识别出你的请求来自非浏览器客户端,做了反爬拦截。浏览器访问时会自动携带一系列请求头(比如User-Agent),而默认的requests请求头很容易被识别为爬虫。

解决方案

1. 添加浏览器请求头

给requests.get()添加模拟浏览器的请求头,核心是User-Agent,也可以补充其他常见头字段,让请求更接近真实浏览器行为:

import requests

pdf_url = "https://www.alexandrina.sa.gov.au/__data/assets/pdf_file/0028/1619614/Council-Special-Meeting-Agenda-11-June-2024.pdf"
pdf_path = 'Test.pdf'

# 模拟Chrome浏览器的请求头
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
    'Accept-Language': 'en-US,en;q=0.5',
    'Accept-Encoding': 'gzip, deflate, br',
    'Connection': 'keep-alive',
    'Upgrade-Insecure-Requests': '1'
}

response = requests.get(pdf_url, headers=headers)
# 先检查响应状态码,确保请求成功
if response.status_code == 200:
    with open(pdf_path, 'wb') as pdf_file:
        pdf_file.write(response.content)
    print("PDF下载成功")
else:
    print(f"请求失败,状态码:{response.status_code}")

2. 保持会话(如果需要)

如果服务器需要验证会话cookie,可以用requests.Session()来维持会话,模拟浏览器的会话状态:

import requests

pdf_url = "https://www.alexandrina.sa.gov.au/__data/assets/pdf_file/0028/1619614/Council-Special-Meeting-Agenda-11-June-2024.pdf"
pdf_path = 'Test.pdf'

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36'
}

session = requests.Session()
session.headers.update(headers)
# 先访问网站首页获取必要的cookie
session.get("https://www.alexandrina.sa.gov.au/")
# 再请求PDF
response = session.get(pdf_url)

if response.status_code == 200:
    with open(pdf_path, 'wb') as pdf_file:
        pdf_file.write(response.content)
    print("PDF下载成功")
else:
    print(f"请求失败,状态码:{response.status_code}")

3. 排查损坏PDF的问题

如果之前下载的PDF损坏,大概率是因为服务器返回的不是PDF内容,而是403错误页面的HTML代码。所以一定要先判断response.status_code是否为200,只有成功的响应才写入文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 15:10:02