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

使用aviationstack API获取航班数据时遇Python列表索引越界问题

问题解决:aviationstack API获取航班数据时IndexError问题

问题背景

使用aviationstack API获取法国马赛机场(ICAO:LFML)所有出港航班,通过总结果数计算分页(每页100条)并批量调用API,但执行flight_data = response.get("data")[counts]时触发IndexError: list index out of range,推测因最后一页结果不足100条导致。

错误原因

  1. 索引越界:response.get("data")是航班数据列表,索引从0开始。counts是当前页的结果总数,比如最后一页返回50条数据,counts=50,此时data[50]超出列表最大索引(49),直接触发索引越界错误。
  2. 逻辑错误:原代码仅尝试获取每个分页的第counts个元素,而非遍历当前页所有航班,完全不符合“获取所有出港航班”的需求。
  3. 分页计算错误:使用round(total_results, -2)计算分页偏移量会生成多余的空分页请求(比如总结果150条,会生成offset=200的请求,返回空数据)。

修复方案

  1. 用math.ceil(total_results / 100)计算正确的总页数,避免多余请求。
  2. 遍历每个分页的data列表,提取所有航班的信息,而非单个元素。
  3. 优化URL构建,使用f-string提升可读性。
  4. 增加基础异常处理,避免API请求失败或字段缺失导致崩溃。

修复后的代码

import requests
import pandas as pd
import math
from pprint import pprint

airport = 'LFML'  # 法国马赛普罗旺斯机场ICAO代码
KEY = "XXX"  # 替换为你的API密钥

all_flights = []

# 获取总结果数,计算分页
base_url = f'http://api.aviationstack.com/v1/flights?access_key={KEY}&dep_icao={airport}'
response = requests.get(base_url)
response.raise_for_status()  # 检查API请求是否成功
resp_data = response.json()
total_results = resp_data["pagination"]["total"]
pprint(f"总共有 {total_results} 条航班数据")

# 计算总页数,每页100条
total_pages = math.ceil(total_results / 100)
pprint(f"需要请求 {total_pages} 页数据")

# 批量请求所有分页
for page in range(total_pages):
    offset = page * 100
    url = f'http://api.aviationstack.com/v1/flights?access_key={KEY}&limit=100&offset={offset}&dep_icao={airport}'
    resp = requests.get(url)
    resp.raise_for_status()
    page_data = resp.json()
    
    # 遍历当前页所有航班
    for flight in page_data["data"]:
        # 提取航班ICAO编号,处理可能的字段缺失
        flight_icao = flight.get("flight", {}).get("icao", "未知")
        all_flights.append(flight_icao)
        pprint(f"提取航班: {flight_icao}")

# 转换为DataFrame
result_df = pd.DataFrame(all_flights, columns=["航班ICAO编号"])
print(result_df)

关键修复点说明

  • 用math.ceil计算总页数,确保只生成必要的分页请求。
  • 遍历page_data["data"]所有元素,获取当前页全部航班信息。
  • 用flight.get("flight", {}).get("icao", "未知")处理字段缺失的情况,避免KeyError。
  • 添加response.raise_for_status()检查API请求状态,快速定位请求失败问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 07:55:33