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

使用urllib.request.urlopen访问网页遇headers参数错误及403如何解决

问题修复方案

第一个报错的根因与修复

urlopen() got an unexpected keyword argument 'headers' 报错是因为urllib.request.urlopen()本身不支持直接传入headers关键字参数,请求头参数需要先封装到urllib.request.Request实例中,再传入urlopen调用。

第二个报错的根因与修复

HTTP Error 403: Forbidden 报错是因为目标网站做了反爬校验,会直接拦截未携带合法User-Agent的请求,移除headers参数后发起的默认请求无有效UA标识,因此被拦截。

正确可运行代码示例

import urllib.request

# 请求头需构造为字典格式,指定User-Agent字段
hdr = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'}
my_url = 'https://www.cms.co.il/catalog/products.aspx?keySearch=9SX3000I'
# 先构造Request对象,绑定url和请求头
req = urllib.request.Request(url=my_url, headers=hdr)
# 将Request对象传入urlopen,设置超时时间
weburl = urllib.request.urlopen(req, timeout=30)
# 读取页面内容
page_content = weburl.read()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 23:54:04