Python的查车票小工具

源码:

"""
Usage:
    tyxkets [-gd]   

Options:
    -h:帮助
    -g:高铁
    -d:动车
    from:出发地
    to:目的地
    date:日期
"""

import docopt
import requests
import re
from prettytable import PrettyTable

args = docopt.docopt(__doc__)

url="https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.8955"
r = requests.get(url, verify=False)

#正则匹配出代号与名字的拼音
stations = re.findall(r'([A-Z]+)\|([a-z]+)',r.text)
stations = dict(stations)
stations = dict(zip(stations.values(),stations.keys()))
#print(stations)

#从命令行参数中拿到出发地,目的地,时间
fromStation = args['']
toStation = args['']
dateTime = args['']

#根据参数匹配出车站代号
fromStation = stations.get(fromStation)
toStation = stations.get(toStation)

#根据出发地目的地时间查询车票
#查询地址:https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate=2016-09-28&from_station=DFT&to_station=BJP
url2 = "https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate="+dateTime+"&from_station="+fromStation+"&to_station="+toStation
print(url2)

r2 = requests.get(url2,verify=False)
ticketsInfo = r2.json()['data']['datas']

# 显示车次、出发/到达站、 出发/到达时间、历时、一等坐、二等坐、软卧、硬卧、硬座
header = 'train station time duration first second softsleep hardsleep hardsit'.split()


def trains():
    for ticket in ticketsInfo:
        train=[
            #车次
            ticket.get('station_train_code'),
            #出发/到达站
            '\n'.join([ticket.get('from_station_name'), ticket.get('to_station_name')]),
            #出发/到达时间
            '\n'.join([ticket.get('start_time'), ticket.get('arrive_time')]),
            #历时
            ticket.get('lishi').replace(":","h")+"m",
            #一等座
            ticket.get('zy_num'),
            #二等座
            ticket.get('ze_num'),
            #软卧
            ticket.get('rw_num'),
            #硬卧
            ticket.get('yw_num'),
            #硬座
            ticket.get('yz_num')
        ]
        yield train

pt = PrettyTable()
#设置每一列的标题
pt._set_field_names(header)
for train in trains():
    pt.add_row(train)
print(pt)

截图:
Python的查车票小工具_第1张图片

用法:python tickets.py
示例:python tickets.py shanghai beijing 2016-10-01

注意:日期中如果是单数,要在前面补0,比如2016年十月一号得写成2016-10-01而不是2016-10-1

会不断完善的,等着吧

你可能感兴趣的:(我的学习笔记)