12306 ticket booking code written using python code

Source: Internet
Author: User
This article mainly introduces the 12306 ticket booking code written using python code and the python code written by myself. It is a very practical technique and has some reference value, you can refer to the example in this article to describe the 12306 ticket booking code written in python code.

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: oldPassengerStr = "name, 34199802036011, 1 _ name, _" # This is the one you need to manually submit your order and f12 will find, locate the post request one by one. The parameter name is passengerTicketStr in the following format: passengerTicketStr = "O, 13683456789, name, name, second, 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 ":" kyf201712306.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}, headers = 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, "passengerTicketStr": Unknown, "randCode": randCode, "tour_flag": "dc"}) checkOrderInfoJson = checkOrderInfoReq. 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 = {" token ": ticketToken," _ json_att ":" "," dwAll ":" N "," key_check_isChange ": key_check_isChange," leftTicketStr ": leftTicket, "oldPassengerStr": oldPassengerStr, "expires": expires, "purpose_codes": purpose_codes, "randCode": randCode, "train_location": train_location}, headers = header) expires = expires. json () print singleForQueueReq. content if si NgleForQueueJson. 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/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 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.cn/otn/confirmPassenger/resultOrderForDcQueue Pass # Check if def checkIsLogin (): checkReq = reqSingle. 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'

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.