又到一年国庆,分享一个自己写的机票价格监控脚本。
使用的是携程的接口,可以搭配青龙面板定时执行,脚本会自动查询价格,并记录历史最低价格,如果价格有降价,会发送通知。
各城市机场代码可以在携程官网查到。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| import requests import lookup from notify import send
def get_lowest_price(dcity, acity): base_url = "https://flights.ctrip.com/itinerary/api/12808/lowestPrice" params = { "flightWay": "Oneway", "dcity": dcity, "acity": acity, "direct": "true", "army": "false" } try: response = requests.get(base_url, params=params) response.raise_for_status() return response.json() except requests.exceptions.RequestException as e: print(f"请求发生错误: {e}") return None
def get_price_by_date(response_data, target_date): """ 获取指定日期的机票价格 参数: response_data: API返回的完整响应数据(字典格式) target_date: 目标日期,格式为'YYYYMMDD'的字符串,如'20250101' 返回: 价格(整数)或None(如果日期不存在) """ try: price_data = response_data['data']['oneWayPrice'][0] if target_date in price_data: return price_data[target_date] else: return None except (KeyError, IndexError): return None
if __name__ == "__main__": lookup.initDB() key = "20251001" result = get_lowest_price("SZX", "WUH") price = get_price_by_date(result, key) print(f"当前机票价格: {price}") history_price = lookup.query_by_code(key) print(f"历史最低机票价格: {history_price}") history_price = history_price if history_price else 99999 if price < int(history_price): print("机票价格有降价,请及时购买!") lookup.upsert(key, price) send('机票价格有降价', f"当前机票价格: {price}"); else: print("机票价格没有降价,请继续等待!")
|