查看火车余票

Jun 26, 2016


###先获取站点名和对应的站点代码

curl --insecure  "https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.8957" | tr '@' '\n' | awk -F"|" '{if (NR > 1){print $2" "$3}}' > city.txt

###现在就可以查询余票了

#!/usr/bin/env python
# coding=utf-8
import getopt,sys 
import requests
import json
from prettytable import PrettyTable 

cityCodeDict={}
table = PrettyTable(['车次', '始发站', '终点站', '发车时间', '到站时间','历时','商务座','特等座','一等座','二等座','高级软卧','软卧','硬卧','软座','硬座','无座','其他','预订'])

myopts=""

def loadCityCode():
    f = open('./city.txt')
    for line in f:
        l = line.strip().split(' ')
        cityCodeDict[l[0]] = l[1]
    f.close()

def printTitle(date):
    print('\033[1;31;40m')
    print(date.replace(" "," "))
    print('\033[0m')

def checkLeftTicket(from_station_name, to_station_name, date):
    #print(from_station_name, to_station_name, date) 
    requestUrl = 'http://www.12306.cn/opn/lcxxcx/query?purpose_codes=ADULT&queryDate='+date+'&from_station='+cityCodeDict[from_station_name]+'&to_station='+cityCodeDict[to_station_name]
    ret=requests.get(requestUrl)
    retDict = json.loads(ret.content)
    retData = retDict['data'] 
    """
    flag
    searchDate
    datas
    """
    if retData['flag'] == True:
        printTitle(retData['searchDate'])
        for key in retData['datas']:
            if myopts == "" or key['station_train_code'][0].lower() in myopts:
                table.add_row((key['station_train_code'],key['from_station_name'],key['to_station_name'],key['start_time'],key['arrive_time'],key['lishi'],key['swz_num'],key['tz_num'],key['zy_num'],key['ze_num'],key['gr_num'],key['rw_num'],key['yw_num'],key['rz_num'],key['yz_num'],key['wz_num'],key['qt_num'],key['canWebBuy']))
        print table


def usage():
    print('---------usage-------')
    print("python {} -[gtdkzh] 起始站 终点站 日期 (python ./ticket.py 上海 北京 2016.06.25)".format(sys.argv[0]))
    print("---options:")
    print('-g , description: 只显示高铁')
    print('-t , description: 只显示特快')
    print('-d , description: 只显示动车')
    print('-k , description: 只显示快车')
    print('-z , description: 只显示直达')
    print('-h , description: show usage')

if __name__ == "__main__":
    try:
        opts, args = getopt.getopt(sys.argv[1:], "gdtkzh")
    except getopt.GetoptError as err:
        print(err) 
        usage()
        sys.exit(2)
    start = ""
    end = ""
    date = ""
    for o, a in opts:
        if o == "-h":
            usage()
            sys.exit(0)
        else:
            myopts += o[1]

    loadCityCode()
    date = args[2]
    date = date.replace('.','-')
    date = date.replace('/','-')
    checkLeftTicket(args[0],args[1],date)