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

Python使用urllib、requests读取URL返回406错误该如何解决?

问题根因

HTTP 406 Not Acceptable 错误是由于请求未携带符合服务端要求的Accept请求头,默认urllib、requests发送的请求中Accept字段不符合目标接口的校验规则,因此被服务端拒绝返回内容。

可行解决代码

1. requests版本(推荐)

构造符合要求的请求头再发起请求:

import requests

link = "http://data.europa.eu/esco/isco/C0110"
headers = {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
}

resp = requests.get(link, headers=headers)
# 校验请求成功后读取内容
if resp.status_code == 200:
    print(resp.text)

2. urllib版本

对应你最初使用的urllib库,修改后代码如下:

import urllib.request

link = "http://data.europa.eu/esco/isco/C0110"
headers = {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
}

req = urllib.request.Request(link, headers=headers)
f = urllib.request.urlopen(req)
myfile = f.read()
print(myfile.decode('utf-8'))
补充说明

如果你需要获取该接口的结构化语义数据,可将Accept字段替换为对应格式标识,比如要获取RDF格式数据,就将Accept值改为application/rdf+xml即可直接拿到对应格式的返回结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 23:54:03