You need to enable JavaScript to run this app. Python使用urllib爬取WSJ等站点出现403 Forbidden错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Python使用urllib爬取WSJ等站点出现403 Forbidden错误如何解决

报错原因

HTTP Error 403: Forbidden 是目标网站的反爬机制拦截了你的请求,urllib 发起请求时默认携带的User-Agent字段为Python-urllib/[你的Python版本号],WSJ等网站识别到请求来自爬虫程序,直接拒绝了访问,而NYT、CNN等网站未配置这层基础校验,所以可以正常爬取。

修复方案(基于原生urllib)

在请求中添加模拟浏览器的请求头,伪装成普通用户访问即可,修改后代码如下:

from urllib.request import urlopen, Request

url = "https://www.wsj.com/articles/peloton-says-wait-times-are-down-to-pre-pandemic-levels-11620334234?mod=hp_lista_pos4"
# 构造自定义请求头,替换默认UA为Chrome浏览器的UA
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"
}
# 构造请求对象
req = Request(url, headers=headers)
page = urlopen(req)
html_bytes = page.read()
html = html_bytes.decode("utf-8")
print(html)
更通用的稳定爬取方案

如果需要适配更多网站的爬取需求,推荐使用requests库,配置更灵活:

  1. 先安装依赖:pip install requests
  2. 示例代码:
import requests

url = "https://www.wsj.com/articles/peloton-says-wait-times-are-down-to-pre-pandemic-levels-11620334234?mod=hp_lista_pos4"
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"
}
response = requests.get(url, headers=headers)
# 自动处理编码转换,直接获取html内容
print(response.text)
其他注意事项

如果修改UA后仍被拦截,可以补充以下配置:

  • 从浏览器的开发者工具中复制该网站请求的完整请求头,补充Referer、Cookie等字段到代码的headers参数中
  • 控制请求频率,两次请求间隔2-3秒,避免IP被临时封禁
  • 遇到需要登录、动态渲染内容的网站,可以使用Selenium、Playwright等模拟浏览器工具发起请求,完全模拟真实用户操作,适配绝大多数网站的访问需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 07:45:04