使用Python 3编写12306余票查询脚本

import os
import json
import requests
from prettytable import PrettyTable
from requests.exceptions import RequestException

def getResponse(url,**kwargs):
    try:
        response = requests.get(url,**kwargs)
        if response.status_code == 200:
            return response
        else:
            return None
    except RequestException:
        return None

def get_stations():
    dirname   = os.path.dirname(__file__)
    file = os.path.join(dirname,"stations.json")
    with open(file,'r',encoding = "utf-8") as json_file:
        stations = json.load(json_file)
        return stations

def getleftTickets(stations,train_date,from_station,to_station):
    query_url   = 'https://kyfw.12306.cn/otn/leftTicket/queryZ'
    Ticket_data = {
        "leftTicketDTO.train_date":  train_date,
        "leftTicketDTO.from_station":from_station,
        "leftTicketDTO.to_station":  to_station,
        "purpose_codes":             "ADULT",
        }
    headers     = {
            'Host': 'kyfw.12306.cn',
            'Referer': 'https://kyfw.12306.cn/otn/leftTicket/init',
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',
            }
    data = getResponse(query_url,params = Ticket_data,headers = headers)

    if data is None:
        print ("访问异常!")
        return None
    
    table = PrettyTable(['车次','始发站','终点站','出发时间','抵达时间','历时','商务座','一等座','二等座','高级软卧','软卧','动卧','硬卧','软座','硬座','无坐','其他'])
    lists = data.json()["data"]["result"]
    for items in lists:
        ticket_info = dict()
        item = items.split('|')#用"|"进行分割
        
        ticket_info['station_train_code'] = item[3]     #车次在3号位置
        ticket_info['from_station_name']  = stations[item[6]]     #始发站信息在6号位置
        ticket_info['to_station_name']    = stations[item[7]]     #终点站信息在7号位置
        ticket_info['start_time']         = item[8]     #出发时间信息在8号位置
        ticket_info['arrive_time']        = item[9]     #抵达时间在9号位置
        ticket_info['last_time']          = item[10]    #经历时间在10号位置
        ticket_info['商务座']             = item[32] or item[25] # 特别注意:商务座在32或25位置
        ticket_info['一等座']             = item[31]    #一等座信息在31号位置
        ticket_info['二等座']             = item[30]    #二等座信息在30号位置
        ticket_info['高级软卧']           = item[21]    #高级软卧信息在31号位置
        ticket_info['软卧']               = item[23]    #软卧信息在23号位置
        ticket_info['动卧']               = item[27]    #动卧信息在27号位置
        ticket_info['硬卧']               = item[28]    #硬卧信息在28号位置
        ticket_info['软座']               = item[24]    #软座信息在24号位置
        ticket_info['硬座']               = item[29]    #硬座信息在29号位置
        ticket_info['无座']               = item[26]    #无座信息在26号位置
        ticket_info['其他']               = item[22]    #其他信息在22号位置

        table.add_row(list(ticket_info.values())) 
    print (table)

if __name__ == "__main__":
    train_info = input("请输入起始站,终点站及出发时间,以空格隔开,格式举例:岳阳 深圳 2019-03-10\n")
    from_station,to_station,train_date = train_info.split()

    stations = get_stations()
    assert(from_station in stations)
    assert(to_station   in stations)

    from_station = stations[from_station]
    to_station   = stations[to_station]
    getleftTickets(stations,train_date,from_station,to_station)

stations.json文件的获取请见上一篇博文。

你可能感兴趣的:(Python,爬虫)