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

求助:芝加哥交通局API在浏览器可正常访问但Python的requests.get请求返回403错误

求助:芝加哥交通局API在浏览器可正常访问但Python的requests.get请求返回403错误

我最近碰到一个棘手的问题:芝加哥交通局(CTA)的API在浏览器里访问完全正常,能拿到200的HTTP状态码,但用Python的requests.get发起请求时,服务器却一直返回403错误。

我调用的API端点是https://lapi.transitchicago.com/api/1.0/ttarrivals.aspx,请求参数包含API密钥、站点ID、最大返回结果数以及输出类型(JSON),CTA的官方开发者文档可在其开发者页面查看。

为了解决这个403问题,我已经尝试过两种方式:

  • 添加模拟浏览器的请求头,直接用requests.get发起请求
  • 使用requests.Session维持会话,并更新了更完整的浏览器请求头

但不管哪种方式,服务器都还是返回403。以下是我尝试过的两段代码:

第一段代码:

url = "https://lapi.transitchicago.com/api/1.0/ttarrivals.aspx"

# Request parameters
params = {
    'key': api_key,
    'mapid': station_id,
    'max': max_results,
    'outputType': output_type
}

# Headers to mimic a browser
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',
    'Accept': 'application/json',
}

try:
    # Make the API request
    response = requests.get(url, params=params, headers=headers)

第二段代码:

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
    'Accept-Language': 'en-US,en;q=0.9',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Connection': 'keep-alive',
    'Upgrade-Insecure-Requests': '1'
}

session = requests.Session()
session.headers.update(headers)
response = session.get(url)

备注:内容来源于stack exchange,提问作者usama

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 19:03:03