这篇实现余票查询。
GET:https://kyfw.12306.cn/otn/index/initMy12306
返回的是html页面,需要的页面内容可以使用HtmlAgilityPack解析html或者正则表达式获取想要的内容;
(1)获取车站信息(GET):https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.8971
返回结果格式为:拼音缩写 | 站名称 | 站代码 | 全拼| 站首字母|站顺序号
var station_names ='@bjb|北京北|VAP|beijingbei|bjb|0
@bjd|北京东|BOP|beijingdong|bjd|1
@bji|北京|BJP|beijing|bj|2
@bjn|北京南|VNP|beijingnan|bjn|3
(2)查询余票初始界面(GET):https://kyfw.12306.cn/otn/leftTicket/init 返回的是html页面,此页面有个参数
CLeftTicketUrl是需要的,余票查询的Url并不是固定的需要根据这个参数来控制;
(3)正式余票查询(GET):
queryUrl =string.Format( "https://kyfw.12306.cn/otn/{0}?leftTicketDTO.train_date={1}&leftTicketDTO.from_station={2}&leftTicketDTO.to_station={3}&purpose_codes={4}", leftTicketUrl, _date, _fromStation.Code, _toStation.Code, _type);
leftTicketUrl为上一步页面参数CLeftTicketUrl的值,
_date出发日期,格式为yyyy-MM-dd,
_fromStation.Code出发站代码,如:VAP
_toStation.Code到达站代码
_type票类型,成人票:ADULT,学生票:0X00
(4) 余票查询返回:
返回的是json,车次信息是在data.result里面,每一条格式为:
"fT5D6f8SMNktk7pyo8kH5uP%2BbMweFedmLFi%2BgOSAsl%2BSWyV%2Ff8NngThSAYTh3zT0gHhb5zci78sx%0AoN64jZ30J6%2FPm4Yy1O2ND01dXvrmxz9PArl6YAgBWAErRCaiHpwvnLnaQXrveO%2FgFkt5wkYq0g08%0AvrMEFZGLwDzKWWkzlj1F%2B0OYunZMDBorKgvo7zgpl5C%2F1CLY3%2FV0vSDdoTMP0NjXDksCTjppWMaw%0AHylZfX5cdC%2F%2F7fCOJ2qSlX5YtoOa|预订|80000G292402|G2924|KOM|IOQ|KOM|IZQ|07:53|14:28|06:35|Y|6HAlNsWAX5zdyJqOx%2FxBsI0llWzyBPa1gjjmKAhkkD1UZguG|20180209|3|M1|01|04|0|0|||||||||||有|15|7||O0M090|OM9|1"
通过"|"分割,0是SecretStr,购票时会用到
ticket.SecretStr = item[0]; ticket.Remark = item[1];//备注:如,预定 ticket.Train_No = item[2];//车辆代码 ticket.Station_Train_Code = item[3];//车次 ticket.From_Station_Name = trainDictionary[item[6]];//起始站代码转站名 ticket.To_Station_Name = trainDictionary[item[7]];//到达站代码转站名 ticket.Start_Time = item[8];//出发时间 ticket.Arrive_Time = item[9];//到底时间 ticket.LastedTime = item[10];//历时 ticket.Gr_Num = ScreenInfo(item[21]);//高级软卧 ticket.Rw_Num = ScreenInfo(item[23]);//软卧 ticket.Rz_Num = ScreenInfo(item[25]);//软座 ticket.Wz_Num = ScreenInfo(item[26]);//无座 ticket.Yw_Num = ScreenInfo(item[28]);//硬卧 ticket.Yz_Num = ScreenInfo(item[29]);//硬座 ticket.Ze_Num = ScreenInfo(item[30]);//二等座 ticket.Zy_Num = ScreenInfo(item[31]);//一等座 ticket.Swz_Num = ScreenInfo(item[32]);//商务座 ticket.Dw_Num = ScreenInfo(item[33]);//动卧