The 12306 ticket booking code written using python code,

Source: Internet
Author: User

The 12306 ticket booking code written using python code,

This article describes the 12306 ticket booking code written in the python code and shares it with you for your reference.

The specific implementation method is as follows:

Import datetimeimport jsonimport reimport sysimport time import Imageimport PyV8import requests import tools. email_helper as emailHelper reload (sys) sys. setdefaultencoding ('utf-8') # @ UndefinedVariablereqSingle = requests. session () attCheCi = ["G655", "G6741", "G67 ", "G491"] # Follow-up times dateList = ["2015-02-18"] # Follow-up date username = "12306 login username" password = "Login password" # This is after you manually submit the order f12 found it by yourself, locate the post request one by one. The parameter name is oldPassengerStr in the following format: old PassengerStr = "name, 34199802036011, 1 _ name, 130434199204238069,1 _" # This is the one you need to manually submit the order and f12 finds by yourself, one by one post request, parameter name: passengerTicketStr format: passengerTicketStr = "O, 13683456789, name, name, Accept, N" header = {"Accept": "text/html, application/xhtml + xml, application/xml; q = 0.9, */*; q = 0.8 "," Accept-Encoding ":" gzip, deflate ", "Accept-Language": "zh-cn, zh; q = 0.8, en-us; q = 0. 5, en; q = 0.3 "," Connection ":" keep-alive "," Host ":" kyf000012306.cn "," Referer ":" https://kyfw.12306.cn/otn/safeguard/init ", "User-Agent": "Mozilla/5.0 (Windows NT 5.1; rv: 34.0) Gecko/20100101 Firefox/34.0" }## train ticket def orderTicket (fromStation, toStation, trainDate, secretStr): header ["Referer"] = "https://kyfw.12306.cn/otn/leftTicket/init" orderInitReq = reqSingle. get ("https://kyfw.12306.cn/otn/leftTicket/init ", Headers = header) header [" Referer "] =" https://kyfw.12306.cn/otn/leftTicket/init "aryKV = extractKey (orderInitReq. content, header) print aryKV # initialize ticket booking header ["Referer"] = "https://kyfw.12306.cn/otn/leftTicket/init" orderInitReq = reqSingle. post ("https://kyfw.12306.cn/otn/leftTicket/submitOrderRequest", data = {aryKV [0]: aryKV [1], "train_date": trainDate, "myversion": "undefined", "purpose_codes ": "ADULT", "query _ From_station_name ": fromStation," query_to_station_name ": toStation," secretStr ": secretStr," tour_flag ":" dc "," back_train_date ": time. strftime ('% Y-% m-% d', time. localtime (time. time (), "undefined": ""}, headers = header) print orderInitReq. content orderInitJson = orderInitReq. json () if orderInitJson. get ("status") = False or orderInitJson. get ("httpstatus ")! = 200: raise Exception ("ticket booking error") initDcReq = reqSingle. post ("https://kyfw.12306.cn/otn/confirmPassenger/initDc", data = {"_ json_att": ""}, headers = header) header ["Referer"] = "https://kyfw.12306.cn/otn/confirmPassenger/initDc" aryKV = extractKey (initDcReq. content, header) match = re. search ("var globalRepeatSubmitToken = '(. *?) '; ", InitDcReq. content) ticketToken = match. group (1) lianxirenReq = reqSingle. post ("https://kyfw.12306.cn/otn/confirmPassenger/getPassengerDTOs", data = {"REPEAT_SUBMIT_TOKEN": ticketToken, "_ json_att": ""}, headers = header) lianxirenJson = lianxirenReq. json () # Verification Code # Start verification code while True: r = reqSingle. get ("https://kyfw.12306.cn/otn/passcodeNew/getPassCodeNew? Module = passenger & rand = randp & ", verify = False, timeout = 5, headers = header) with open (" orderRand.jpg "," wb ") as rimg: rimg. write (r. content) pass img = Image. open ("orderRand.jpg") img. show () randCode = raw_input ("Enter the logon Verification Code:") # verify the verification code randReq = reqSingle. post ("https://kyfw.12306.cn/otn/passcodeNew/checkRandCodeAnsyn", data = {"REPEAT_SUBMIT_TOKEN": ticketToken, "_ json_att": "", "rand": "randp", "randCode": randCode}, head Ers = header) randRes = randReq. json () if randRes. get ("status") and randRes. get ("httpstatus") = 200 and randRes. get ("data "). get ("result") = "1": break; pass print "the verification code is entered correctly! "# Check the ticket checkOrderInfoReq = reqSingle. post ("https://kyfw.12306.cn/otn/confirmPassenger/checkOrderInfo", data = {aryKV [0]: aryKV [1], "REPEAT_SUBMIT_TOKEN": ticketToken, "_ json_att": "", "bed_level_order_num ": "000000000000000000000000000000", "cancel_flag": 2, "oldPassengerStr": oldPassengerStr, "average": average, "randCode": randCode, "tour_flag": "dc"}) checkOrderInfoJson = checkOrderInfo Req. json () if checkOrderInfoJson. get ("status") = False or checkOrderInfoJson. get ("httpstatus ")! = 200: raise Exception ("check ticket errors") pass fromStationTelecode = re. search ("'from _ station_telecode ':'(.*?) '", InitDcReq. content). group (1) leftTicket = re. search (" 'ypinfodetail ':'(.*?) '", InitDcReq. content). group (1) purpose_codes = re. search (" 'purpose _ codes ':'(.*?) '", InitDcReq. content). group (1) station_train_code = re. search (" 'Station _ train_code ':'(.*?) '", InitDcReq. content). group (1) to_station_telecode = re. search ("' to _ station_telecode ':'(.*?) '", InitDcReq. content). group (1) train_no = re. search (" 'train _ no ':'(.*?) '", InitDcReq. content ). group (1) queueCountReq = reqSingle. post ("https://kyfw.12306.cn/otn/confirmPassenger/getQueueCount", data = {"identifier": ticketToken, "_ json_att": "", "identifier": fromStationTelecode, "leftTicket": leftTicket, "purpose_codes ": purpose_codes, "seatType": 0, "stationTrainCode": station_train_code, "toStationTelecode": to_station_telecode, "train_date": datetime. datetime. Fromtimestamp (time. mktime (time. strptime (trainDate, '% Y-% m-% D '))). strftime ('% a % B % d % Y % H: % M: % S GMT + 0800'), "train_no": train_no}, headers = header) queueCountJson = queueCountReq. json () print queueCountReq. content if queueCountJson. get ("status") = False or queueCountJson. get ("httpstatus ")! = 200: raise Exception ("Get queue error") # confirm queue key_check_isChange = re. search ("'key _ check_ischang ':'(.*?) '", InitDcReq. content). group (1) train_location = re. search (" 'train _ location ':'(.*?) '", InitDcReq. content ). group (1) singleForQueueReq = reqSingle. post ("https://kyfw.12306.cn/otn/confirmPassenger/confirmSingleForQueue", data = {"REPEAT_SUBMIT_TOKEN": ticketToken, "_ json_att": "", "dwAll": "N", "key_check_isChange": key_check_isChange, "leftTicketStr": leftTicket, "oldPassengerStr": oldPassengerStr, "passengerTicketStr": Signature, "purpose_codes": purpose_codes, "randCode": randCode ," Train_location ": train_location}, headers = header) singleForQueueJson = singleForQueueReq. json () print singleForQueueReq. content if singleForQueueJson. get ("status") = False or singleForQueueJson. get ("httpstatus ")! = 200: raise Exception ("confirmSingleForQueue Exception") if singleForQueueJson. get ("data") is None or singleForQueueJson. get ("data "). get ("submitStatus") = False: raise Exception ("confirmSingleForQueue Exception") # Wait For orderid while True: orderWaitReq = reqSingle. get ("https://kyfw.12306.cn/otn/confirmPassenger/queryOrderWaitTime", data = {"REPEAT_SUBMIT_TOKEN": ticketToken, "_ json_att": "", "random": time. time (), "tourFlag ": "Dc"}, headers = header) print orderWaitReq. content orderWaitJson = orderWaitReq. json () if orderWaitJson. get ("status") and orderWaitJson. get ("httpstatus") = 200: if orderWaitJson. get ("data") is not None and orderWaitJson. get ("data "). get ("orderId") is not None: orderId = orderWaitJson. get ("data "). get ("orderId") break pass # enter the queue dcQueueReq = reqSingle. post ("https://kyfw.12306.cn/otn/confirmPassenger/res UltOrderForDcQueue ", data = {" token ": ticketToken," _ json_att ":" "," orderSequence_no ": orderId}, headers = header) dcQueueJson = dcQueueReq. json () if dcQueueJson. get ("status") and dcQueueJson. get ("httpstatus") == 200 and dcQueueJson. get ("data") is not None and dcQueueJson. get ("data "). get ("submitStatus"): print "ticket booking successful" pass else: print dcQueueJson. content print "ticket booking failed" pass # https://kyfw.12306.c N/otn/confirmPassenger/resultOrderForDcQueue pass # Check whether def checkIsLogin (): checkReq = reqSingle is logged on. post ("https://kyfw.12306.cn/otn/login/checkUser", data = {"_ json_att": ""}, headers = header) print u "check for Logon" + checkReq. content checkReqJson = checkReq. json () if checkReqJson. get ("status") and checkReqJson. get ("httpstatus") = 200: if checkReqJson. get ("data") is not None and checkReqJson. get ("data "). get ("flag "): Return True pass return False pass # extract the key and valuedef extractKey (htmlContent, headerxx) after the js encrypted content: loginMatch = re. search (R' <script src = "(/otn/dynamicJs /. *?) "Type =" text/javascript "xml: space =" preserve "> </script> ', htmlContent) jsUrl =" https://kyfw.12306.cn "+ loginMatch. group (1) jsReq = reqSingle. get (jsUrl, verify = False, timeout = 15, headers = headerxx) jsContent = jsReq. content jsMatch = re. search ("(function bin216 .*?) Function aj ", jsContent) jsEncode = jsMatch. group (1) # obtain the encrypted js content keyMatch = re. search (" var key = '(.*?) '", JsContent) loginKey = keyMatch. group (1) # obtain the logon key ctx = PyV8.JSContext () ctx. enter () ctx. eval (jsEncode) loginValue = ctx. locals. encode32 (ctx. locals. bin216 (ctx. locals. base32.encrypt ("1111", loginKey) return [loginKey, loginValue] pass # login operation def login (): header ["Referer"] = "https://kyfw.12306.cn/otn/login/init" r = reqSingle. get ("https://kyfw.12306.cn/otn/login/init", verify = False, timeout = 15, headers = header) LoginContent = r. content aryKV = extractKey (loginContent, header) # start to do the Verification Code while True: r = reqSingle. get ("https://kyfw.12306.cn/otn/passcodeNew/getPassCodeNew? Module = login & rand = sjrand & ", verify = False, timeout = 5, headers = header) with open (" loginRand.jpg "," wb ") as rimg: rimg. write (r. content) pass img = Image. open ("loginRand.jpg") img. show () randCode = raw_input ("Enter the logon Verification Code:") # verify the verification code randReq = reqSingle. post ("https://kyfw.12306.cn/otn/passcodeNew/checkRandCodeAnsyn", data = {"rand": "sjrand", "randCode": randCode}, headers = header) randRes = randReq. json () if randRes. get ("stat Us ") and randRes. get ("httpstatus") = 200 and randRes. get ("data "). get ("result") = "1": break; pass print "the verification code is entered correctly! "# Log on to loginRes = reqSingle. post ("https://kyfw.12306.cn/otn/login/loginAysnSuggest", data = {aryKV [0]: aryKV [1], "loginUserDTO. user_name ": username," userDTO. password ": password," randCode ": randCode," myversion ":" undefined "," randCode_validate ":" "}, headers = header) print repr (r. request) print loginRes. content loginResJson = loginRes. json () if loginResJson. get ("status") and loginResJson. get ("httpstatus") = 2 00: if loginResJson. get ("data") is not None and loginResJson. get ("data "). get ("loginCheck") = "Y": print "Logon successful" else: raise Exception (loginRes. content) else: login () passdef checkTicket (dtStr): print dt while True: try: r = requests. get ("https://kyfw.12306.cn/otn/leftTicket/queryT? LeftTicketDTO. train_date = "+ dtStr +" & leftTicketDTO. from_station = BXP & leftTicketDTO. to_station = HDP & purpose_codes = ADULT ", verify = False, timeout = 5, headers = header) break failed t Exception: pass # print r. contentfd print r. content try: queryDataJson = json. loads (r. content) Does T Exception: return if queryDataJson ["httpstatus"] = 200 and queryDataJson ["status"]: # print queryDataJson ["data"] for checi in qu EryDataJson ["data"]: tmpData = checi ["queryLeftNewDTO"] trainCode = tmpData. get ("station_train_code") # yzNum = tmpData. get ("yz_num") yzNum = tmpData. get ("ze_num") if trainCode in attCheCi: if yzNum! = "--" And yzNum! = "NONE" and (yzNum = "" or int (yzNum)> = 2): # send an email fromStation = tmpData. get ("start_station_name") toStation = tmpData. get ("end_station_name") secretStr = checi. get ("secretStr") orderTicket (fromStation, toStation, dtStr, secretStr) # body = dtStr + "-" + trainCode + "-" + yzNum + u "hard seat" # print body # mailer = emailHelper. email_helper ("smtp.qq.com", "fd", "fss", "qq.com", "plain") # mailer. send ("630419595@qq.com", u "with train tickets", body) # raise Exception ("with tickets ") pass print trainCode + yzNum pass passif _ name _ = '_ main _': # login () # if checkIsLogin (): # print "Logon successful" # orderTicket ("Beijing West", "Handan East", "", "login") # exit () login () if checkIsLogin (): print "Logon successful" while True: checkCount = 0 for dt in dateList: checkTicket (dt) time. sleep (2) checkCount + = 1 if checkCount % 10 = 0: if checkIsLogin (): print "success" else: print "kicked" pass

Have you ever obtained a ticket to go home for the Chinese New Year?

I hope this article will help you with Python programming.

Articles you may be interested in:
  • Php allows you to query the remaining 12306 train tickets and query the price (12306 train tickets)
  • Php provides more than 12306 ticket query and price query examples
  • Example of querying train ticket remaining by capturing 12306 information in java
  • Python login 12306 Simulation Method
  • 12306 dynamic verification code inspired by ASP. NET to implement dynamic GIF Verification Code (with source code)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.