This article describes the Python code written by the 12306 booking code, share to everyone for your reference.
The 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"] #关注的车次dateList =["2015-02-18"] #关注的日期username = "12306 login username" password= "Login Password" #这个是需要手动提交订单后f12自己找的, each POST request to find, parameter name: OLDPASSENGERSTR format as follows oldpassengerstr= "name, 1,130434199802036011,1_ name 2,1,130434199204238069,1_ "#这个是需要手动提交订单后f12自己找的, each POST request to find, the parameter name is: PASSENGERTICKETSTR The format is as follows Passengerticketstr= "o,0,1, Name, 1,130434199802036011,13683456789,n_o,0,1, name 2,1,130434199204238069,13683456789 , 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 ":" KYFW .12306.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 "}# #定火车票 def orderticket (fromstation,tostation,traindate,secretstr): header[" Ref Erer "]=" 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 #初始化订票 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_statio N_name ": Tostation, "Secretstr": Secretstr, "Tour_flag": "DC", "Back_train_date": Time.strftime ('%y-%m-%d ', Time.localtime (Time.time ())), "U Ndefined ":" "},headers=header) print orderinitreq.content Orderinitjson=orderin Itreq.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) Lian Xirenreq=reqsingle.post ("Https://kyfw.12306.cn/otn/confirmPassenger/getPassengerDTOs", data={"Repeat_submit_ TOKEN ": Tickettoken," _json_att ":" "},headers=header) LianxirEnjson=lianxirenreq.json () #验证码 #开始做验证码 while True:r=reqsingle.get ("Https://kyfw.12306.cn/otn/passcodeNew/getPassC odenew?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 ( "Please enter the login Verification code:") #验证验证码 randreq= reqsingle.post ("Https://kyfw.12306.cn/otn/passcodeNew/checkRandCodeAnsyn", data={ "Repeat_submit_token": Tickettoken, "_json_att": "", "Rand": "RANDP", "Randcode": Randcode},headers=header) Randres=randreq.json () If Randres.get ("status") and Randres.get ("https Tatus ") ==200 and Randres.get (" data "). Get (" result ") = =" 1 ": Break; Pass print "Verification code entered correctly!" "#检查票 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, "Passengerticketstr":p assengerticketstr, "Randc Ode ": Randcode," Tour_flag ":" DC "}) CH Eckorderinfojson=checkorderinforeq.json () If Checkorderinfojson.get ("status") ==false or Checkorderinfojson.get (" Httpstatus ")!=200:raise Exception (" Check ticket error ") 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={" Repeat_submit_token " : Tickettoken, "_json_att": "", "Fromstati Ontelecode ": Fromstationtelecode," Leftticket ": Leftticket, "Purpose_codes":p urpose_codes, "Seattype": 0, "Stationtraincode": Station_train_code, "Tostationtelecode": To_station_telecode, "Train_da TE ":d atetime.datetime.fromtimestamp (Time.mktime (Time.strptime (traindate, '%y-%m-%d ')). Strftime ('%a%b%d%Y%h:%m: %s gmt+0800 '), "train_no": Train_no},hea Ders=header) Queuecountjson=queuecountreq.json () print queuecountreq.content if Queuecountjson.get ("status") ==False or Queuecountjson.get ("Httpstatus")!=200:raise Exception ("Get queue error") #确认队列 key_check_ischange=re.search ("' Key_check _ischange ': ' (. *?) ' ", 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": Lefttick ET, "oldpassengerstr": Oldpassengerstr, "Passengerticketstr":p assengerticketstr, "Purpose_codes":p urpose_codes, "Randcode": Randcode, "Train_location": train_location },headers=header) Singleforqueuejson=singleforqueuereq.json () print singleforqueuereq.content if SingleForQueue Json.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 ") #等待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 ord Erwaitjson=orderwaitreq.json () If Orderwaitjson.get ("status") and Orderwaitjson.get ("Httpstatus") ==200:if OrderWa Itjson.get ("Data") is not None and orderwaitjson.get ("data"). Get ("OrderId") was not none:orderid=orderwaitjson.get ( "Data"). Get ("OrderId") Break pass pass #进入队列 dcqueuereq=reqsingle.post ("https://kyfw.12306.cn/otn/confirm Passenger/resultorderfordcqueue ", data={ "Repeat_submit_token": Tickettoken, "_json_att": "", "Ordersequence_no": OrderId} , Headers=header) Dcqueuejson=dcqueuereq.json () If Dcqueuejson.get ("status") and Dcqueuejson.get ("Httpstatus") ==200 A nd dcqueuejson.get ("data") is not None and dcqueuejson.get ("data"). Get ("Submitstatus"): print "booking successful" pass else: Print dcqueuejson.content print "Booking failed" pass #https://kyfw.12306.cn/otn/confirmpassenger/resultorderfordcqueue pass# Check if you are signed in to Def Checkislogin (): checkreq= reqsingle.post ("Https://kyfw.12306.cn/otn/login/checkUser", data={"_json_ Att ":" "},headers=header" Print U "check whether to log in" +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 ("fl AG "): Return True pass REturn False pass# Extract JS encrypted content after key and Valuedef Extractkey (HTMLCONTENT,HEADERXX): Loginmatch=re.search (R ', 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) #获取加密的js内容 keymatch=re.search (" Var key= ' (. *?) ' ", jscontent) loginkey= Keymatch.group (1) #获取登录的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) #开始做验证码 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 Login 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 ("status") and Randres.get ("Httpstatus") ==200 and Randres.get ("Data"). g ET ("result") = = "1": Break; Pass print "Verification code entered correctly!" "#开始登陆 loginres=reqsingle.post (" Https://kyfw.12306.cn/otn/login/loginAysnSuggest ", data={ Arykv[0]:arykv[1], "loginuserdto.user_name": Username, "Userdto.password":p assword, "Randcode": Randcode, "Myversion": "Undefined", "randcode_validate": "" },headers=header) print repr (r.request) print loginres.content Loginresjson=loginr Es.json () If Loginresjson.get ("status") and Loginresjson.get ("Httpstatus") ==200:if loginresjson.get ("data") is not NE and Loginresjson.get ("data"). Get ("logincheck") = = "Y": print "Login 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 except Excepti On:pass Pass #print r.contentfd print r.content try:querydatajson= json.loads (r.content) except Exception : Return if querydatajson["Httpstatus"]==200 and querydatajson["status"]: #print querydatajson["Data"] for CHEC I in querydatajson["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==" with "or int (yznum) >=2): #发邮件 fromstation=tmpdata.get ("Start_station_name") tostation=tmpdata.get ("E Nd_station_name ") secretstr=checi.get (" Secretstr ") Orderticket (Fromstation, Tostation, Dtstr, SECRETSTR) # body=dtstr+ "-" +traincode+ "-" +yznum+u "Hard Seats" # Print body# mailer=emailhelper.email_helper ("SM Tp.qq.com "," FD "," FSS "," qq.com "," plain ") # Mailer.send (" 630419595@qq.com ", U" have train tickets ", body) # Raise Exce Ption ("with tickets") Pass print Traincode+yznum Pass pass passif __name__ = = ' __main__ ': # login () # if Checkislogin (): # print "Login Successful" # # Orderticket ("Beijing West", "Handan East", "2015-01-14", "mjaxns0wms0xncmwmcnhnjczmsmwmjoxnsmwnzowns Myndawmec2nzmxmdujqlhqi0Hqucmwotoymcpljjfkuqzopb8j6ykv6yo45licizaxiza2i08wmdawmda4mthnmdawmdawmtewotawmdawmdayninqmimxnde5mdg2otu2mta0izi5nei0qky 0qtu2ode2rdu1mze5rkrcrkveqzq3mzk2mueyruewoem0muvcmjzgmdc3ruuynzc0 ") # exit () login () if Checkislogin (): print" Login Successful " While true:checkcount=0-DT in datelist:checkticket (DT) Time.sleep (2) checkcount+=1 if CH Eckcount%10==0:if checkislogin (): print "Success status" Else:print "kicked" pass pass
Have you got the tickets for the New Year's trip home?
Hopefully this article will help you with Python programming.