標籤:
1.資料介面
https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate=2016-08-01&from_station=NCG&to_station=CZQ
返回的是2015-8-01南昌到郴州的火車票資訊,格式為json。
資料類似如下:
{ "validateMessagesShowId":"_validatorMessage", "status":true,"httpstatus":200, "data":{ "datas":[ { "train_no":"5u000G140101", "station_train_code":"G1401", "start_station_telecode":"NXG", "start_station_name":"南昌西", "end_station_telecode":"IZQ", "end_station_name":"廣州南", "from_station_telecode":"NXG", "from_station_name":"南昌西", "to_station_telecode":"ICQ", "to_station_name":"郴州西", "start_time":"07:29", "arrive_time":"10:42", "day_difference":"0", ... "swz_num":"無" }, { ... } ]}
2.擷取GZ到深圳火車票資料
import requestsimport jsonclass trainTicketsSprider: def getTicketsInfo(self,purpose_codes,queryDate,from_station,to_station): self.url = ‘https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=%s&queryDate=%s&from_station=%s&to_station=%s‘ %(purpose_codes,queryDate,from_station,to_station) self.headers = { "Accept":"text/html,application/xhtml+xml,application/xml;", "Accept-Encoding":"gzip", "Accept-Language":"zh-CN,zh;q=0.8", "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36" } self.TicketSession = requests.Session() self.TicketSession.verify = False #關閉https驗證 self.TicketSession.headers = self.headers try: self.resp_json = self.TicketSession.get(self.url) self.ticketsDatas = json.loads(self.resp_json.text)["data"]["datas"] return self.ticketsDatas except Exception as e: print(e)def isZero(num): if num == ‘--‘ or ‘無‘: return ‘0‘ else: return numdef main(): purpose_codes = ‘ADULT‘ queryDate = ‘2016-08-01‘ from_station = ‘GZQ‘ to_station = ‘SZQ‘ TicketSprider = trainTicketsSprider() res= TicketSprider.getTicketsInfo(purpose_codes,queryDate,from_station,to_station) for i,ticketInfo in enumerate(res): print(u"車次:%s" %ticketInfo["station_train_code"]) print(u"起始站:%s" %ticketInfo["start_station_name"]) print(u"目的地:%s" %ticketInfo["to_station_name"]) print(u"開車時間:%s" %ticketInfo["start_time"]) print(u"到達時間:%s" %ticketInfo["arrive_time"]) print(u"二等座還剩:%s張票" %(ticketInfo["ze_num"])) print(u"一等座還剩:%s張票" % (ticketInfo["zy_num"])) print(u"商務座還剩:%s張票" %(ticketInfo["swz_num"]))print(u"無座還剩:%s張票" %(ticketInfo["wz_num"])) print(u"是否有票:%s" %ticketInfo["canWebBuy"]) print("**********************************")if __name__ == ‘__main__‘: main()
結果如下:
車次:G6205
起始站:廣州南
目的地:深圳北
開車時間:07:20
到達時間:07:57
二等座還剩:708張票
一等座還剩:108張票
商務座還剩:24張票
無座還剩:無張票
是否有票:Y
Requests抓取火車票資料