def _init(self): url = r'https://kyfw.12306.cn/otn/login/init' headers = { 'User-Agent': FIREFOX_USER_AGENT, 'Referer': r'https://kyfw.12306.cn/otn/index/initMy12306', 'Connection': 'keep-alive', } NetUtils.get(self.__session, url, headers=headers)
def _userLogin(self): url = r'https://kyfw.12306.cn/otn/login/userLogin' params = { '_json_att': '', } headers = { 'User-Agent': FIREFOX_USER_AGENT, 'Content-Type': 'application/x-www-form-urlencoded', 'Referer': 'https://kyfw.12306.cn/otn/login/init', } NetUtils.get(self.__session, url, params=params, headers=headers)
def _getExtraInfo(self): url = r'https://kyfw.12306.cn/otn/confirmPassenger/{}'.format( '%s' % ('initWc' if self.__ticket.tourFlag == TourFlag.GO_BACK else 'initDc')) print(url) def getRepeatSubmitToken(html): repeatSubmitToken = re.findall( r"var globalRepeatSubmitToken = '(.*)'", html)[0] print('RepeatSubmitToken = %s' % repeatSubmitToken) return repeatSubmitToken html = NetUtils.get(self.__session, url, headers={ 'User-Agent': FIREFOX_USER_AGENT, 'Connection': 'keep-alive', }).text # print('getExtraInfo', html) self.__ticket.repeatSubmitToken = getRepeatSubmitToken(html) def decodeTicketInfoForPassengerForm(html): ticketInfoForPassengerForm = re.findall( r'var ticketInfoForPassengerForm=(.*);', html)[0] return json.loads(ticketInfoForPassengerForm.replace("'", "\"")) self.__ticket.ticketInfoForPassengerForm = decodeTicketInfoForPassengerForm( html)
def _payOrderInfo(self): url = r'https://kyfw.12306.cn/otn/payOrder/init?random=%d' % (time.time() * 1000) headers = { 'User-Agent': FIREFOX_USER_AGENT, 'Connection': 'keep-alive', } response = NetUtils.get(self.__session, url, headers=headers).text
def query(session, trainDate, fromStation, toStation, passengerType=PASSENGER_TYPE_ADULT): params = { r'leftTicketDTO.train_date': trainDate, r'leftTicketDTO.from_station': city2code(fromStation), r'leftTicketDTO.to_station': city2code(toStation), r'purpose_codes': passengerType } # response = NetUtil.normalGet(Query.__url, params=params, headers={'User-Agent': random.choice(USER_AGENT)}).json() headers = { 'User-Agent': FIREFOX_USER_AGENT, 'Referer': r'https://kyfw.12306.cn/otn/leftTicket/init', 'Connection': 'keep-alive', } response = NetUtils.get(session, Query.__url, params=params, headers=headers, verify=False) print(response.text) response = response.json() response = response['data'] if 'data' in response else Log.e( "can not find key: 'data'") queryResults = response['result'] if 'result' in response else Log.e( "can not find key: 'result'") return Query.__decode(queryResults, passengerType)
def logOut(self): self._loginOut() self._init() url = r'https://kyfw.12306.cn/passport/web/auth/uamtk' formData = { 'appid': 'otn', } headers = { 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Connection': 'keep-alive', # 'Content-Length': '9', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Host': 'kyfw.12306.cn', 'Origin': 'https://kyfw.12306.cn', 'Referer': 'https://kyfw.12306.cn/otn/login/init', 'User-Agent': FIREFOX_USER_AGENT, 'X-Requested-With': 'XMLHttpRequest', # 'Cookie':'_passport_session=3cae58f596b644f88b96ee8a448d9a737285; uamtk=7GdEj-S-9ZKfqcRkEjwCr6PLf4-SAiHRlY-wVm5sNnKizqTunx1210; RAIL_EXPIRATION=1515462916653; RAIL_DEVICEID=FH21u6JKmLVmsSwBvxOHIgRrgouY7azS3ENBUEL6aJKO9p3ou041Nv1QgAkLWHrWeeNJikYEgiZFKXUKXvaAJuRlxCN2sGDaKAkqZ2XKq8zhLtTpRZ8XcXkHXAdtirM4xzuuFesSAAWlg8gBZ37z_bF-N0VxtHo3; _jc_save_fromStation=%u6DF1%u5733%u5317%2CIOQ; _jc_save_toStation=%u6F6E%u6C55%2CCBQ; _jc_save_fromDate=2018-01-08; _jc_save_toDate=2018-01-08; _jc_save_showIns=true; _jc_save_wfdc_flag=dc; route=9036359bb8a8a461c164a04f8f50b252; BIGipServerotn=451936778.64545.0000; BIGipServerpool_passport=300745226.50215.0000' } response = NetUtils.post(self.__session, url, data=formData, headers=headers) # response = NetUtils.NormalPost(url, data=formData, headers=headers) pprint(response.request.headers) print(response.text) return response.json()
def _passportRedirect(self): url = r'https://kyfw.12306.cn/otn/passport?redirect=/otn/login/userLogin' params = { 'redirect': '/otn/login/userLogin', } headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'en-US,en;q=0.5', 'User-Agent': FIREFOX_USER_AGENT, 'Referer': 'https://kyfw.12306.cn/otn/login/init', 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1', } NetUtils.get(self.__session, url, params=params, headers=headers)
def _loginAsyncSuggest(self, userName, userPwd): captcha = Captcha(self.__session) results, verify = captcha.verifyCaptchaByHand( type=TYPE_LOGIN_OTHER_WAY) if not verify: return False, '验证码识别错误!' url = r'https://kyfw.12306.cn/otn/login/loginAysnSuggest' formData = { 'loginUserDTO.user_name': userName, 'userDTO.password': userPwd, 'randCode': results, } headers = { 'User-Agent': FIREFOX_USER_AGENT, 'Referer': r'https://kyfw.12306.cn/otn/login/init', 'Connection': 'keep-alive', 'Content-Type': r'application/x-www-form-urlencoded; charset=UTF-8', } response = NetUtils.post(self.__session, url, data=formData, headers=headers) print('loginAsyncSuggest: %s' % response.text) response = response.json() def isSuccess(response): return response['status'] and response['data'][ 'loginCheck'] == 'Y', response['data']['otherMsg'] loginSuccess, otherMsg = isSuccess(response) return loginSuccess, '%s:%s' % (userName, otherMsg or '登录成功!')
def _payOrderInfo(self): url = r"https://kyfw.12306.cn/otn//payOrder/init?random=%10d" % ( time.time() * 1000) headers = { "User-Agent": FIREFOX_USER_AGENT, "Connection": "keep-alive" } response = NetUtils.get(self.__session, url, headers=headers).text
def _payOrderInfo(self): url = r'https://kyfw.12306.cn/otn//payOrder/init?random=%10d' % ( time.time() * 1000) headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0', 'Connection': 'keep-alive', } response = NetUtils.get(self.__session, url, headers=headers).text
def _getQueueCount(self): url = r'https://kyfw.12306.cn/otn/confirmPassenger/getQueueCount' formData = { # Thu+Jan+04+2018+00:00:00+GMT+0800 # 'train_date': datetime.strptime( # self.__ticket.ticketInfoForPassengerForm['queryLeftTicketRequestDTO']['train_date'], '%Y%m%d').strftime( # '%b+%a+%d+%Y+00:00:00+GMT+0800'), # Mon Jan 08 2018 00:00:00 GMT+0800 (中国标准时间) 'train_date': datetime.strptime( self.__ticket.ticketInfoForPassengerForm[ 'queryLeftTicketRequestDTO']['train_date'], '%Y%m%d').strftime('%b %a %d %Y 00:00:00 GMT+0800') + ' (中国标准时间)', 'train_no': self.__ticket.ticketInfoForPassengerForm[ 'queryLeftTicketRequestDTO']['train_no'], 'stationTrainCode': self.__ticket.trainNo, 'seatType': self.__ticket.seatType, 'fromStationTelecode': self.__ticket.fromStationCode, 'toStationTelecode': self.__ticket.toStationCode, 'leftTicket': self.__ticket.ticketInfoForPassengerForm['leftTicketStr'], 'purpose_codes': self.__ticket.ticketInfoForPassengerForm['purpose_codes'], 'train_location': self.__ticket.ticketInfoForPassengerForm['train_location'], '_json_att': '', 'REPEAT_SUBMIT_TOKEN': self.__ticket.repeatSubmitToken, } headers = { 'User-Agent': FIREFOX_USER_AGENT, 'Referer': r'https://kyfw.12306.cn/otn/confirmPassenger/initDc', 'Connection': 'keep-alive', } response = NetUtils.post(self.__session, url, data=formData, headers=headers).json() return response['status'], response['messages'], \ response['data']['ticket'] if 'data' in response and 'ticket' in response['data'] else -1, \ response['data']['count'] if 'data' in response and 'count' in response['data'] else -1
def isLogin(self): url = r'https://kyfw.12306.cn/otn/login/checkUser' headers = { 'User-Agent': FIREFOX_USER_AGENT, 'Referer': r'https://kyfw.12306.cn/otn/leftTicket/init', 'Connection': 'keep-alive', } formData = {'_json_att': ''} response = NetUtils.post(self.__session, url, formData, headers=headers) response = response.json() if response else None return response['data'][ 'flag'] if response and 'data' in response and 'flag' in response[ 'data'] else False
def _getPassengerDTOs(self): self._getExtraInfo() url = r'https://kyfw.12306.cn/otn/confirmPassenger/getPassengerDTOs' formData = { '_json_att': '', 'REPEAT_SUBMIT_TOKEN': self.__ticket.repeatSubmitToken, } response = NetUtils.post(self.__session, url, data=formData, headers={ 'User-Agent': FIREFOX_USER_AGENT, 'Connection': 'keep-alive', }).json() passengersList = response['data']['normal_passengers'] return response['status'] if 'status' in response else False, \ response['messages'] if 'messages' in response else '无法获取乘客信心,请先进行添加!', \ self.__getPassengerInfo(passengersList)
def _uamtk(self): url = r'https://kyfw.12306.cn/passport/web/auth/uamtk' headers = { 'Referer': r'https://kyfw.12306.cn/otn/passport?redirect=/otn/login/userLogin', 'User-Agent': FIREFOX_USER_AGENT, 'Connection': 'keep-alive', } response = NetUtils.post(self.__session, url, data={ 'appid': 'otn' }).json() def isSuccess(response): return response[ 'result_code'] == 0 if 'result_code' in response else False return isSuccess(response), \ response['result_message'] if 'result_message' in response else 'no result_message', \ response['newapptk'] if 'newapptk' in response else 'no newapptk'
def _uamauthclient(self, apptk): url = r'https://kyfw.12306.cn/otn/uamauthclient' headers = { 'Referer': r'https://kyfw.12306.cn/otn/passport?redirect=/otn/login/userLogin', 'User-Agent': FIREFOX_USER_AGENT, 'Connection': 'keep-alive', } response = NetUtils.post(self.__session, url, data={'tk': apptk}, headers=headers) print(response.text) response = response.json() def isSuccess(response): return response[ 'result_code'] == 0 if 'result_code' in response else False return isSuccess(response), '%s:%s' % (response['username'], response['result_message'])
def _queryOrderWaitTime(self): url = r'https://kyfw.12306.cn/otn/confirmPassenger/queryOrderWaitTime' params = { 'random': '%10d' % (time.time() * 1000), 'tourFlag': self.__ticket.ticketInfoForPassengerForm['tour_flag'] or 'dc', '_json_att': '', 'REPEAT_SUBMIT_TOKEN': self.__ticket.repeatSubmitToken, } headers = { 'User-Agent': FIREFOX_USER_AGENT, 'Referer': r'https://kyfw.12306.cn/otn/confirmPassenger/initDc', 'Connection': 'keep-alive', } response = NetUtils.get(self.__session, url, params=params, headers=headers).json() print('queryOrderWaitTime: %s' % response) return response['status'], response['messages'], response['data']['waitTime'], response['data']['orderId'], \ response['data']['msg'] if 'msg' in response['data'] else None
def __query(trainDate, fromStation, toStation, passengerType=PASSENGER_TYPE_ADULT): params = { r'leftTicketDTO.train_date': trainDate, r'leftTicketDTO.from_station': city2code(fromStation), r'leftTicketDTO.to_station': city2code(toStation), r'purpose_codes': passengerType } response = NetUtils.normalGet(Query.__url, params=params, headers={ 'User-Agent': random.choice(USER_AGENT) }).json() response = response['data'] if 'data' in response else Log.e( "can not find key: 'data'") queryResults = response['result'] if 'result' in response else Log.e( "can not find key: 'result'") return Query.__decode(queryResults, passengerType)
def _checkOrderInfo(self, passengersDetails, seatType, ticketTypeCodes=1): url = r'https://kyfw.12306.cn/otn/confirmPassenger/checkOrderInfo' # self.__ticket.seatType = seatType # self.__ticket.ticketTypeCodes = ticketTypeCodes # self.passengerDetails = passengerDetails formData = { 'cancel_flag': self.__ticket.ticketInfoForPassengerForm['orderRequestDTO'] ['cancel_flag'] or '2', 'bed_level_order_num': self.__ticket.ticketInfoForPassengerForm['orderRequestDTO'] ['bed_level_order_num'] or '000000000000000000000000000000', 'passengerTicketStr': TrainUtils.passengerTicketStrs(seatType, passengersDetails, ticketTypeCodes), 'oldPassengerStr': TrainUtils.oldPassengerStrs(passengersDetails), 'tour_flag': self.__ticket.ticketInfoForPassengerForm['tour_flag'] or 'dc', 'randCode': '', 'whatsSelect': '1', '_json_att': '', 'REPEAT_SUBMIT_TOKEN': self.__ticket.repeatSubmitToken, } headers = { 'User-Agent': FIREFOX_USER_AGENT, 'Referer': r'https://kyfw.12306.cn/otn/confirmPassenger/initDc', 'Connection': 'keep-alive', } response = NetUtils.post(self.__session, url, formData, headers=headers).json() return response['status'], response['messages'], response['data']['submitStatus'], \ response['data']['errMsg'] if 'errMsg' in response['data'] else 'submit falied'
def _resultOrderForDcOrWcQueue(self, orderSequenceNo): url = r'https://kyfw.12306.cn/otn/confirmPassenger/{}'.format( 'resultOrderForWcQueue' if self.__ticket.tourFlag == TourFlag.GO_BACK else 'resultOrderForDcQueue') formData = { 'orderSequence_no': orderSequenceNo, '_json_att': '', 'REPEAT_SUBMIT_TOKEN': self.__ticket.repeatSubmitToken, } headers = { 'User-Agent': FIREFOX_USER_AGENT, 'Referer': r'https://kyfw.12306.cn/otn/confirmPassenger/initDc', 'Connection': 'keep-alive', } response = NetUtils.post(self.__session, url, data=formData, headers=headers) print('resultOrderForDcOrWcQueue', response.text) response = response.json() return response['status'], response['messages'], response['data'][ 'submitStatus']
def _loginNormal(self, userName, userPwd): url = r'https://kyfw.12306.cn/passport/web/login' captcha = Captcha(self.__session) if not captcha.verifyCaptchaByHand()[1]: return False, '验证码识别错误!' headers = { 'Referer': r'https://kyfw.12306.cn/otn/login/init', 'User-Agent': FIREFOX_USER_AGENT, 'Connection': 'keep-alive', 'Content-Type': r'application/x-www-form-urlencoded; charset=UTF-8', } payload = { 'username': userName, 'password': userPwd, 'appid': 'otn', } response = NetUtils.post(self.__session, url, data=payload, headers=headers) response = response.json() if response else None Log.v('loginResponse: %s' % response) def isLoginSuccess(responseJson): return 0 == responseJson[ 'result_code'] if responseJson and 'result_code' in responseJson else False if not isLoginSuccess(response): return False self._passportRedirect() self._userLogin() result, msg, apptk = self._uamtk() if not Utils.check(result, msg): return False return self._uamauthclient(apptk)
def _confirmSingleOrGoForQueue(self, passengersDetails): url = r'https://kyfw.12306.cn/otn/confirmPassenger/confirmGoForQueue' if self.__ticket.tourFlag == TourFlag.GO_BACK \ else r'https://kyfw.12306.cn/otn/confirmPassenger/confirmSingleForQueue' formData = { 'passengerTicketStr': TrainUtils.passengerTicketStrs(self.__ticket.seatType, passengersDetails, self.__ticket.ticketTypeCodes), 'oldPassengerStr': TrainUtils.oldPassengerStrs(passengersDetails), 'randCode': '', 'purpose_codes': self.__ticket.ticketInfoForPassengerForm['purpose_codes'], 'key_check_isChange': self.__ticket.ticketInfoForPassengerForm['key_check_isChange'], 'leftTicketStr': self.__ticket.ticketInfoForPassengerForm['leftTicketStr'], 'train_location': self.__ticket.ticketInfoForPassengerForm['train_location'], 'choose_seats': '', # todo::how to choose seats 'seatDetailType': '000', # todo::make clear 000 comes from 'whatsSelect': '1', 'roomType': '00', # todo::make clear this value comes from 'dwAll': 'N', '_json_att': '', 'REPEAT_SUBMIT_TOKEN': self.__ticket.repeatSubmitToken, } headers = { 'User-Agent': FIREFOX_USER_AGENT, 'Referer': r'https://kyfw.12306.cn/otn/confirmPassenger/{}'.format( 'initWc' if self.__ticket.tourFlag == TourFlag.GO_BACK else 'initDc'), 'Connection': 'keep-alive', r'Accept': r'application/json, text/javascript, */*; q=0.01', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'en-US,en;q=0.5', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Host': 'kyfw.12306.cn', 'X-Requested-With': 'XMLHttpRequest', } response = NetUtils.post(self.__session, url, data=formData, headers=headers).json() return response['status'], response['messages'], response['data'][ 'submitStatus'], response['data'][ 'errMsg'] if 'errMsg' in response['data'] else None