12306火车票购票软件大家都用过,怎么用Python写一个命令行的火车票查看器,要求在命令行敲一行命令来获得你想要的火车票信息,下面通过本文学习吧。
Python火车票查询器
[img]http://files.jb51.net/file_images/article/201704/201704200937398.jpg[/img]
[b]接口设置[/b]
先给这个小应用起个名字吧,既然及查询票务信息,那就叫它tickets
我们希望用户只要输入出发站,到达站以及日期就让就能获得想要的信息,所以tickets应该这样被使用:
[img]http://files.jb51.net/file_images/article/201704/201704200937399.jpg[/img]
最终[code] $ tickets [-gdtkz] from to date[/code]
[b]开发环境
[/b]
用virtualenv建立虚拟环境,用Python3开发,
$ virtualenv -p /usr/bin/python3 venv
通过下面的命令激活它:
[b]解析参数[/b]
Python有很多写命令行应用的工具,我们选用docopt这个简单易用的工具,我们先安装它:
docopt可以按我们在文档字符串中定义的格式来解析参数,
[img]http://files.jb51.net/file_images/article/201704/2017042009373910.jpg[/img]
[img]http://files.jb51.net/file_images/article/201704/2017042009373911.jpg[/img]
[b]获取数据[/b]
[img]http://files.jb51.net/file_images/article/201704/2017042009373912.jpg[/img]
[url=https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate=2016-07-01&from_station=SHH&to_station=BJP]https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate=2016-07-01&from_station=SHH&to_station=BJP[/url]
[img]http://files.jb51.net/file_images/article/201704/2017042009373913.jpg[/img]
[url=https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.8955]https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.8955[/url]
保存stations.html
[img]http://files.jb51.net/file_images/article/201704/2017042009373914.jpg[/img]
[img]http://files.jb51.net/file_images/article/201704/2017042009373915.jpg[/img]
[img]http://files.jb51.net/file_images/article/201704/2017042009373916.jpg[/img]
[img]http://files.jb51.net/file_images/article/201704/2017042009373917.jpg[/img]
[b]显示结果[/b]
prettytable这个库可以让我们它像MySQL数据库那样格式化显示数据
$ pip3 install prettytable
[img]http://files.jb51.net/file_images/article/201704/2017042009373918.jpg[/img]
以上所述是小编给大家介绍的python实现12306火车票查询器,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对编程素材网网站的支持!