携程网机票查询 携程机票订单生成器

以前参考别人的代码,用Python做了一个12306命令行式的火车票查询工具,感觉还挺有意思的!于是自己又做了一个类似的——携程机票查询器。

携程官网查询的效果是这样的:

Python命令行界面查询的效果是这样的:

输入出发地、目的地、乘机日期,即可看到可选的航班、机场、出发到达时间、票价等信息。

视频演示效果如下:

重播播放00:00/00:00正在直播00:00进入全屏50点击按住可拖动视频

程序的源码如下:

1.air_stations.py2.airline_ticket.py

1.air_stations.py

1.air_stations.pyimportreimportosimportjsonimportrequestsfrompprintimportpprint

url =http://webresource.c-ctrip.com/code/cquery/resource/address/flight/flight_new_poi_gb2312.js?CR_2017_07_18_00_00_00response = requests.get(url,verify=False)

station = re.findall(u([u4e00-u9fa5]+)(([A-Z]+)), response.text)

stations = dict(station)

pprint(stations,indent =4)

2.airline_ticket.py

2.airline_ticket.py此程序可用于查询携程机票,查询需要指定出发日期、出发城市、目的城市!(模仿了12306火车订票查询程序)importrequests,json,osfromdocoptimportdocoptfromprettytableimportPrettyTablefromcoloramaimportinit,Forefromair_stationsimportstations

fromCity = input(Please input the city you want leave

toCity = input(Please input the city you will arrive

tripDate = input(Please input the date(Example:2017-09-27)

init()classTrainsCollection:header =航空公司 航班 机场 时间 机票价格 机场建设费.split()def__init__(self,airline_tickets):self.airline_tickets = airline_tickets@propertydefplains(self):航空公司的总表没有找到,但是常见航空公司也不是很多就暂时用这个dict{air_company}来收集!如果strs没有查询成功,则会返回一个KeyError,表示此dict中未找到目标航空公司,则会用其英文代码显示!air_company = {"G5":"华夏航空","9C":"春秋航空","MU":"东方航空","NS":"河北航空","HU":"海南航空","HO":"吉祥航空","CZ":"南方航空","FM":"上海航空","ZH":"深圳航空","MF":"厦门航空","CA":"中国国航","KN":"中国联航"}foriteminself.airline_tickets:try:

strs = air_company[item[alc]]exceptKeyError:

strs = item[alc]

airline_data = [

Fore.BLUE + strs + Fore.RESET,

Fore.BLUE + item[fn] + Fore.RESET,n.join([Fore.YELLOW + item[dpbn] + Fore.RESET,

Fore.CYAN + item[apbn] + Fore.RESET]),n.join([Fore.YELLOW + item[dt] + Fore.RESET,

Fore.CYAN + item[at] + Fore.RESET]),

item[lp],

item[tax],

]yieldairline_datadefpretty_print(self):PrettyTable()用于在屏幕上将查询到的航班信息表逐行打印到终端pt = PrettyTable()

pt._set_field_names(self.header)forairline_datainself.plains:

pt.add_row(airline_data)

print(pt)defdoit():headers = {"Cookie":"自定义","User-Agent":"自定义",

}

arguments = {from:fromCity,to:toCity,date:tripDate

}

DCity1 = stations[arguments[from]]

ACity1 = stations[arguments[to]]

DDate1 = arguments[date]

url = ("http://flights.ctrip.com/domesticsearch/search/SearchFirstRouteFlights?DCity1={}&ACity1={}&SearchType=S&DDate1={}").format(DCity1,ACity1,DDate1)try:

r = requests.get(url,headers = headers,verify=False)exceptExceptionase:

print(repr(e))

print(url)

airline_tickets = r.json()[fis]

TrainsCollection(airline_tickets).pretty_print()if__name__ ==__main__:

doit()

其实,此小程序还可以拓展,譬如将查询记录存到本地电脑(txt格式、或者存到数据库里)或者更厉害的还可以设置定时自动查询;还可以设置查询到自动发邮箱提醒;还可以用Python的GUI库将此程序做成桌面软件的形式。。。。

学点编程,好处多多

搜索建议: