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

遍历机场ID列表批量调用航班API失败,报400参数错误求解决

问题分析与修复方案

核心错误点

  • 变量引用错误:循环里你写了f"airports/{airports}/flights",这里应该用当前循环的airport变量而非整个列表airports;同时你的airports是二维列表(每个元素是['HLZN']这类单元素列表),必须取airport[0]才能拿到真实的机场ID。
  • 缩进错误:if和else块内的代码没有正确缩进,Python对缩进敏感,这会直接导致语法错误。
  • 方法调用错误:response.json是方法对象,必须加括号调用response.json()才能获取返回的JSON数据;且错误分支中如果返回非200状态码,直接调用response.json()可能抛出异常,需要额外处理。

修正后的代码

import requests
import pandas as pd
import time

apiKey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx' 
apiUrl = 'https://xxxxxxxxxxxxxxxxxxx.com/xxxxxxx/' 
auth_header = {'x-apikey': apiKey}

# 改成一维列表更简洁,避免索引操作
airports = ['HLZN', 'HLLQ', 'HLLB', 'HLGT', 'HLMS', 'HLLS', 'HLTQ', 'HLLT', 'HLLM'] 
payload = {'max_pages': 1}

json_responses = []

for airport_id in airports:
    try:
        # 拼接正确的API地址,使用当前循环的机场ID
        response = requests.get(
            f"{apiUrl}airports/{airport_id}/flights",
            params=payload,
            headers=auth_header
        )
        response.raise_for_status()  # 自动触发HTTP错误(如400、404等)
        flight_data = response.json()
        print(f"成功获取机场{airport_id}的航班数据")
        # 如果API返回的是列表而非字典,把append改成extend
        json_responses.append(flight_data)
    except requests.exceptions.RequestException as e:
        print(f"获取机场{airport_id}数据失败: {str(e)}")
    # 处理5000个机场必须加延迟,避免触发API限流
    time.sleep(1)

# 生成DataFrame
if json_responses:
    all_acct_df = pd.DataFrame(json_responses)
    # 可选:保存数据到文件
    # all_acct_df.to_csv('all_airport_flights.csv', index=False)
else:
    print("未获取到任何有效数据")

额外注意事项

  • 列表结构优化:将二维列表改为一维列表,遍历更直接,减少不必要的索引操作。
  • 异常处理:加入try-except捕获所有请求相关异常(网络错误、API返回非JSON格式等),避免程序中途崩溃。
  • 请求限流:处理5000个机场时,必须用time.sleep()控制请求频率,否则极易被API服务商判定为恶意请求导致IP封禁。延迟时间可参考API文档的限流规则,一般1-3秒即可。
  • 数据结构适配:如果API返回的是列表类型数据,需把append替换为extend,确保最终DataFrame结构正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 22:55:16