以前参考别人的代码,用Python做了一个12306命令行式的火车票查询工具,感觉还挺有意思的!于是自己又做了一个类似的携程机票查询器。 携程官网查询的效果是这样的: Python命令行界面查询的效果是这样的: 输入出发地、目的地、乘机日期,即可看到可选的航班、机场、出发到达时间、票价等信息。 视频演示效果如下: 重播播放00:0000:00正在直播00:00进入全屏50点击按住可拖动视频 程序的源码如下: 1。airstations。py2。airlineticket。py 1。airstations。py 1。airstations。pyimportreimportosimportjsonimportrequestsfrompprintimportpprint urlhttp:webresource。cctrip。comcodecqueryresourceaddressflightflightnewpoigb2312。js?CR20170718000000responserequests。get(url,verifyFalse) stationre。findall(u(〔u4e00u9fa5〕)((〔AZ〕)),response。text) stationsdict(station) pprint(stations,indent4) 2。airlineticket。py 2。airlineticket。py此程序可用于查询携程机票,查询需要指定出发日期、出发城市、目的城市!(模仿了12306火车订票查询程序)importrequests,json,osfromdocoptimportdocoptfromprettytableimportPrettyTablefromcoloramaimportinit,Forefromairstationsimportstations fromCityinput(Pleaseinputthecityyouwantleave toCityinput(Pleaseinputthecityyouwillarrive tripDateinput(Pleaseinputthedate(Example:20170927) init()classTrainsCollection:header航空公司航班机场时间机票价格机场建设费。split()definit(self,airlinetickets):self。airlineticketsairlineticketspropertydefplains(self):航空公司的总表没有找到,但是常见航空公司也不是很多就暂时用这个dict{aircompany}来收集!如果strs没有查询成功,则会返回一个KeyError,表示此dict中未找到目标航空公司,则会用其英文代码显示!aircompany{G5:华夏航空,9C:春秋航空,MU:东方航空,NS:河北航空,HU:海南航空,HO:吉祥航空,CZ:南方航空,FM:上海航空,ZH:深圳航空,MF:厦门航空,CA:中国国航,KN:中国联航}foriteminself。airlinetickets:try: strsaircompany〔item〔alc〕〕exceptKeyError: strsitem〔alc〕 airlinedata〔 Fore。BLUEstrsFore。RESET, Fore。BLUEitem〔fn〕Fore。RESET,n。join(〔Fore。YELLOWitem〔dpbn〕Fore。RESET, Fore。CYANitem〔apbn〕Fore。RESET〕),n。join(〔Fore。YELLOWitem〔dt〕Fore。RESET, Fore。CYANitem〔at〕Fore。RESET〕), item〔lp〕, item〔tax〕, 〕yieldairlinedatadefprettyprint(self):PrettyTable()用于在屏幕上将查询到的航班信息表逐行打印到终端ptPrettyTable() pt。setfieldnames(self。header)forairlinedatainself。plains: pt。addrow(airlinedata) print(pt)defdoit():headers{Cookie:自定义,UserAgent:自定义, } arguments{from:fromCity,to:toCity,date:tripDate } DCity1stations〔arguments〔from〕〕 ACity1stations〔arguments〔to〕〕 DDate1arguments〔date〕 url(http:flights。ctrip。comdomesticsearchsearchSearchFirstRouteFlights?DCity1{}ACity1{}SearchTypeSDDate1{})。format(DCity1,ACity1,DDate1)try: rrequests。get(url,headersheaders,verifyFalse)exceptExceptionase: print(repr(e)) print(url) airlineticketsr。json()〔fis〕 TrainsCollection(airlinetickets)。prettyprint()ifnamemain: doit() 其实,此小程序还可以拓展,譬如将查询记录存到本地电脑(txt格式、或者存到数据库里)或者更厉害的还可以设置定时自动查询;还可以设置查询到自动发邮箱提醒;还可以用Python的GUI库将此程序做成桌面软件的形式。。。。 学点编程,好处多多