如何在Python中调用XML格式的航班价格查询API?
Python调用XML格式航班API实操指南
一、请求API获取XML数据
用requests库发送HTTP请求(具体用GET还是POST,以航空公司API文档要求为准),获取XML格式的响应内容。
示例代码:
import requests # 按API要求组装请求参数 request_params = { 'dep_city': 'PEK', 'arr_city': 'SHA', 'flight_date': '2024-10-01' } # 必要时添加认证信息(比如API Key放在请求头里) headers = {'Authorization': 'Bearer YOUR_API_KEY'} response = requests.get('YOUR_AIRLINE_API_URL', params=request_params, headers=headers, timeout=10) response.encoding = 'utf-8' xml_raw = response.text
二、解析XML数据
Python有两种常用的XML解析方案,按需选择:
方案1:用内置xml.etree.ElementTree
无需额外安装,适合结构简单的XML:
import xml.etree.ElementTree as ET # 解析XML字符串 root = ET.fromstring(xml_raw) # 根据API返回的XML结构提取数据(示例需自行调整节点路径) for flight_node in root.findall('.//FlightInfo'): flight_no = flight_node.find('FlightNumber').text lowest_price = flight_node.find('LowestPrice/Amount').text currency = flight_node.find('LowestPrice/Currency').text print(f"航班 {flight_no} 最低价格:{lowest_price} {currency}")
方案2:用lxml(推荐复杂XML场景)
先通过pip install lxml安装,支持XPath语法,解析更灵活:
from lxml import etree # 解析XML内容 root = etree.fromstring(xml_raw.encode('utf-8')) # 用XPath精准提取数据 flights = root.xpath('//FlightInfo') for flight in flights: flight_no = flight.xpath('./FlightNumber/text()')[0] price_info = flight.xpath('./LowestPrice')[0] price = price_info.xpath('./Amount/text()')[0] currency = price_info.xpath('./Currency/text()')[0] print(f"航班 {flight_no} 最低价格:{price} {currency}")
三、关键注意事项
- 严格遵循航空公司API文档:确认请求方式、参数格式、认证规则(比如API Key的放置位置)
- 处理命名空间:如果XML带有命名空间(如
<ns:Flight>),解析前需注册命名空间,例如ET.register_namespace('ns', 'http://example.com/flight') - 添加异常处理:捕获网络超时、HTTP错误、XML解析错误等情况,避免程序崩溃:
try: response = requests.get(...) response.raise_for_status() # 触发HTTP错误异常 root = ET.fromstring(xml_raw) except requests.exceptions.RequestException as e: print(f"请求出错:{e}") except ET.ParseError as e: print(f"XML解析错误:{e}")
附:链接页面内容翻译
中国南方航空运价服务说明
本页面为用户介绍南航的运价体系及相关服务细节,核心内容包括:
- 运价规则详解:不同舱位的定价标准,以及与退改签政策绑定的运价条款
- 特殊运价适用范围:针对团体旅客、常旅客、军人/学生等特殊群体的专属优惠运价
- 运价查询工具使用指南:指导用户通过官方渠道查询实时有效的航班运价
- 常见问题解答:解答运价变更、特殊运价申请流程等用户高频疑问
内容的提问来源于stack exchange,提问作者Erik Johnsson
相关产品推荐
相关产品推荐

