上一篇抓取12306上火车站点英文缩写的续集
# -*- coding: UTF-8 -*-
import requests
from ceshi_result import stations
from prettytable import PrettyTable
def Get_train_text():
# from_station = stations.get(input('Please enter where you a from:'))
from_station = 'CWQ' #调试用
# to_station = stations.get(input('Please enter where you want to go:'))
to_station='IOQ' #调试用
# date = input('Please enter the date you wang to inquire:')
date = '2018-06-02' #调试用
url = ('https://kyfw.12306.cn/otn/leftTicket/query?'
'leftTicketDTO.train_date={}&'
'leftTicketDTO.from_station={}&'
'leftTicketDTO.to_station={}&'
'purpose_codes=ADULT').format(date,from_station,to_station)
r = requests.get(url)
trains_text = r.json()['data']['result']
# print(trains_text)
return trains_text
def Get_train_information():
key_list = []
value_list = []
table = PrettyTable()
table._set_field_names('车次 出发地点 到达地点 出发时间 到达时间 历时 一等 二等 软卧 硬卧 硬座 无座'.split())
for key,value in stations.items():
key_list.append(key)
value_list.append(value)
for raw_train in Get_train_text():
data_list = raw_train.split('|')
train_number = data_list[3] #车次
from_station_code = data_list[6] #始发站信息
to_station_code = data_list[7] #终点站信息
from_station_index = value_list.index(from_station_code)
to_station_index = value_list.index(to_station_code)
from_station_name = key_list[from_station_index]
to_station_name = key_list[to_station_index]
start_time = data_list[8] #出发时间
arrive_time = data_list[9] #到达时间
time_duration = data_list[10] #历时
first_class_seat = data_list[31] #一等座
second_class_seat = data_list[30] #二等座
soft_sleeper = data_list[23] or '--' #软卧
hard_sleeper = data_list[28] or '--' #硬卧
hard_seat= data_list[29] or '--' #硬座
no_seat = data_list[26] or '--' #无座
table.add_row([
train_number,
from_station_name,
to_station_name,
start_time,
arrive_time,
time_duration,
first_class_seat,
second_class_seat,
soft_sleeper,
hard_sleeper,
hard_seat,
no_seat
])
print (table)
if __name__ == '__main__':
Get_train_information()