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

调用JSON API遇HTTP 403错误,请求获取罗切斯特理工学院plus_code

解决OpenGeo API 403 Forbidden错误并提取plus_code

问题原因

出现403错误是因为urllib默认的请求头会被服务器识别为非浏览器请求,直接拦截了。只需在请求里加上模拟浏览器的User-Agent头就能解决。

修正后的完整代码

import urllib.parse
import urllib.request
import json

# 目标地点:罗切斯特理工学院
address = "罗切斯特理工学院"
api_url = "http://py4e-data.dr-chuck.net/opengeo"

# 编码地址参数
params = urllib.parse.urlencode({'q': address})
full_url = f"{api_url}?{params}"

# 构造请求,添加User-Agent头
req = urllib.request.Request(
    full_url,
    headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'}
)

try:
    with urllib.request.urlopen(req) as response:
        data = json.load(response)
        # 提取首个plus_code
        if data and 'plus_code' in data[0]:
            print(f"罗切斯特理工学院的plus_code:{data[0]['plus_code']}")
        else:
            print("未找到对应的plus_code")
except urllib.error.HTTPError as e:
    print(f"请求错误:{e}")
except json.JSONDecodeError:
    print("解析JSON数据失败")

代码说明

  • 用urllib.parse.urlencode()正确编码地址参数,避免乱码问题
  • 通过Request对象添加User-Agent头,模拟浏览器请求,绕过服务器拦截
  • 解析返回的JSON数据,取第一个结果中的plus_code字段
  • 加入异常处理,捕获请求和解析过程中可能出现的错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 10:53:10