又到一年国庆,分享一个自己写的机票价格监控脚本。

使用的是携程的接口,可以搭配青龙面板定时执行,脚本会自动查询价格,并记录历史最低价格,如果价格有降价,会发送通知。

各城市机场代码可以在携程官网查到。

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() # 返回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__":
# 从深圳(SZX)到武汉(WUH)的例子
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("机票价格没有降价,请继续等待!")