12306购票

# -*- coding: utf-8 -*-
"""
Created on Wed May  9 14:12:25 2018
@author: JJ
"""
#12306账号
myuser=""
mypasswd=""
import urllib.request
import re
import ssl
import urllib.parse
import http.cookiejar
import datetime
import time
ssl._create_default_https_context = ssl._create_unverified_context
areatocode={"上海":"SHH","北京":"BJP","南京":"NJH","昆山":"KSH","杭州":"HZH","桂林":"GLZ"}
start1=input"请输入起始站:")
start=areatocode[start1]
to1=input"请输入到站:")
to=areatocode[to1]
isstudent=input"是学生吗?是:1,不是:0")
date=input"请输入要查询的乘车开始日期的年月,如1997-10-07:")
ifisstudent=="0"):
    student="ADULT"
else:
    student="0X00"
url="https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date="+date+"&
leftTicketDTO.from_station="+start+"&leftTicketDTO.to_station="+to+"&purpose_codes="+student
context = ssl._create_unverified_context)
data=urllib.request.urlopenurl).read).decode"utf-8","ignore")
patrst01='"result":[.*?)]'
rst01=re.compilepatrst01).findalldata)[0]
allcheci=rst01.split",")
checimap_pat='"map":{.*?})'
checimap=evalre.compilechecimap_pat).findalldata)[0])
print"车次	出发站名	到达站名	出发时间	到达时间	一等座	二等座	硬座	无座")
for i in range0,lenallcheci)):
    try:
        thischeci=allcheci[i].split"|")
        code=thischeci[3]
        fromname=thischeci[6]
        fromname=checimap[fromname]
        toname=thischeci[7]
        toname=checimap[toname]
        stime=thischeci[8]
        atime=thischeci[9]
        yz=thischeci[31]
        wz=thischeci[30]
        ze=thischeci[29]
        zy=thischeci[26]
        printcode+"	"+fromname+"	"+toname+"	"+stime+"	"+atime+"	"+strzy)+"	"+strze)+"	
              "+stryz)+"	"+strwz))
    except Exception as err:
        pass
isdo=input"查票完成,请输入1继续…")
ifisdo==1 or isdo=="1"):
    pass
else:
    raise Exception"输入不是1,结束执行")
print"Cookie处理中…")
cjar=http.cookiejar.CookieJar)
opener = urllib.request.build_openerurllib.request.HTTPCookieProcessorcjar))
urllib.request.install_openeropener)
loginurl="https://kyfw.12306.cn/otn/login/init#"
req0 = urllib.request.Requestloginurl)
req0.add_header'User-Agent', 'Mozilla/5.0 Windows NT 6.1; WOW64) AppleWebKit/537.36 KHTML, lik
e Gecko) Chrome/38.0.2125.122 Safari/537.36 SE 2.X MetaSr 1.0')
req0data=urllib.request.urlopenreq0).read).decode"utf-8","ignore")
yzmurl="https://kyfw.12306.cn/passport/captcha/captcha-image?login_site=E&module=login&rand=sjrand"
while True:
    urllib.request.urlretrieveyzmurl,"图片路径")
    yzm=input"请输入验证码,输入第几张图片即可")
    ifyzm!="re"):
        break
pat1='".*?)"'
allpic=re.compilepat1).findallyzm)
def getxypic):
    ifpic==1):
        xy=35,45)
    ifpic==2):
        xy=112,45)
    ifpic==3):
        xy=173,45)
    ifpic==4):
        xy=253,45)        
    ifpic==5):
        xy=35,114)
    ifpic==6):
        xy=112,114)
    ifpic==7):
        xy=173,114)
    ifpic==8):
        xy=253,114)
    return xy
allpicpos=""
for i in allpic:
    thisxy=getxyinti))
    for j in thisxy:
        allpicpos=allpicpos+strj)+","
allpicpos2=re.compile".*?).$").findallallpicpos)[0]
printallpicpos2)
yzmposturl="https://kyfw.12306.cn/passport/captcha/captcha-check"
yzmpostdata =urllib.parse.urlencode{
"answer":allpicpos2,
"rand":"sjrand",
"login_site":"E",
}).encode'utf-8')
req1 = urllib.request.Requestyzmposturl,yzmpostdata)
req1.add_header'User-Agent', 'Mozilla/5.0 Windows NT 6.1; WOW64) AppleWebKit/537.36 KHTML, lik
e Gecko) Chrome/38.0.2125.122 Safari/537.36 SE 2.X MetaSr 1.0')
req1data=urllib.request.urlopenreq1).read).decode"utf-8","ignore")
loginposturl="https://kyfw.12306.cn/passport/web/login"
loginpostdata =urllib.parse.urlencode{
"username":myuser,
"password":mypasswd,
"appid":"otn",
}).encode'utf-8')
req2 = urllib.request.Requestloginposturl,loginpostdata)
req2.add_header'User-Agent', 'Mozilla/5.0 Windows NT 6.1; WOW64) AppleWebKit/537.36 KHTML, lik
e Gecko) Chrome/38.0.2125.122 Safari/537.36 SE 2.X MetaSr 1.0')
req2data=urllib.request.urlopenreq2).read).decode"utf-8","ignore")
loginposturl2="https://kyfw.12306.cn/otn/login/userLogin"
loginpostdata2 =urllib.parse.urlencode{
"_json_att":"",
}).encode'utf-8')
req2_2 = urllib.request.Requestloginposturl2,loginpostdata2)
req2_2.add_header'User-Agent', 'Mozilla/5.0 Windows NT 6.1; WOW64) AppleWebKit/537.36 KHTML, lik
e Gecko) Chrome/38.0.2125.122 Safari/537.36 SE 2.X MetaSr 1.0')
req2data_2=urllib.request.urlopenreq2_2).read).decode"utf-8","ignore")
 
#loginposturl3="https://kyfw.12306.cn/passport/web/auth/uamtk"
 
 
loginposturl4="https://kyfw.12306.cn/otn/uamauthclient"
loginpostdata4 =urllib.parse.urlencode{
"tk":"cli2f6l6ey0neIVsR_moEUOUHtyMFxiOFhQpnAnxy2y0",
}).encode'utf-8')
req2_4 = urllib.request.Requestloginposturl4,loginpostdata4)
req2_4.add_header'User-Agent', 'Mozilla/5.0 Windows NT 6.1; WOW64) AppleWebKit/537.36 KHTML, lik
e Gecko) Chrome/38.0.2125.122 Safari/537.36 SE 2.X MetaSr 1.0')
req2data_4=urllib.request.urlopenreq2_4).read).decode"utf-8","ignore")
 
centerurl="https://kyfw.12306.cn/otn/index/initMy12306"
req3 = urllib.request.Requestcenterurl)
req3.add_header'User-Agent', 'Mozilla/5.0 Windows NT 6.1; WOW64) AppleWebKit/537.36 KHTML, lik
e Gecko) Chrome/38.0.2125.122 Safari/537.36 SE 2.X MetaSr 1.0')
req3data=urllib.request.urlopenreq3).read).decode"utf-8","ignore")
print"登陆完成")
 
isdo=input"如果需要订票,请输入1继续,否则请输入其他数据")
ifisdo==1 or isdo=="1"):
    pass
else:
    raise Exception"输入不是1,结束执行")
thiscode=input"请输入要预定的车次:")
chooseno="None"
 
while True:
    try:
        
        initurl="https://kyfw.12306.cn/otn/leftTicket/init"
        reqinit=urllib.request.Requestiniturl)
        reqinit.add_header'User-Agent', 'Mozilla/5.0 Windows NT 6.1; WOW64) AppleWebKit/537.3
6 KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36 SE 2.X MetaSr 1.0')
        initdata=urllib.request.urlopenreqinit).read).decode"utf-8","ignore")
        
        bookurl="https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date="+date+"&leftTi
cketDTO.from_station="+start+"&leftTicketDTO.to_station="+to+"&purpose_codes="+student
        req4 = urllib.request.Requestbookurl)
        req4.add_header'User-Agent', 'Mozilla/5.0 Windows NT 6.1; WOW64) AppleWebKit/537.36 KHT
ML, like Gecko) Chrome/38.0.2125.122 Safari/537.36 SE 2.X MetaSr 1.0')
        req4data=urllib.request.urlopenreq4).read).decode"utf-8","ignore")
        
        patrst01='"result":[.*?)]'
        rst01=re.compilepatrst01).findallreq4data)[0]
        allcheci=rst01.split",")
        checimap_pat='"map":{.*?})'
        checimap=evalre.compilechecimap_pat).findallreq4data)[0])
        code=[]
        secretStr=[]
        zy=[]
        for i in range0,lenallcheci)):
            try:
                thischeci=allcheci[i].split"|")
                thiscode1=thischeci[3]
                code.appendthiscode1)
                secretStr.appendthischeci[0].replace'"',""))
                thiszy=thischeci[31]
                zy.appendthiszy)
            except Exception as err:
                pass
        trainzy={}
        for i in range0,lencode)):
            trainzy
]
=zy[i] traindata={} for i in range0,lencode)): traindata
]
=secretStr[i] checkurl="https://kyfw.12306.cn/otn/login/checkUser" checkdata =urllib.parse.urlencode{ "_json_att":"" }).encode'utf-8') req5 = urllib.request.Requestcheckurl,checkdata) req5.add_header'User-Agent', 'Mozilla/5.0 Windows NT 6.1; WOW64) AppleWebKit/537.3 6 KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36 SE 2.X MetaSr 1.0') req5data=urllib.request.urlopenreq5).read).decode"utf-8","ignore") backdate=datetime.datetime.now) backdate=backdate.strftime"%Y-%m-%d") submiturl="https://kyfw.12306.cn/otn/leftTicket/submitOrderRequest" submitdata =urllib.parse.urlencode{ "secretStr":traindata[thiscode], "train_date":date, "back_train_date":backdate, "tour_flag":"dc", "purpose_codes":student, "query_from_station_name":start1, "query_to_station_name":to1, }) submitdata2=submitdata.replace"%25","%") submitdata3=submitdata2.encode'utf-8') req6 = urllib.request.Requestsubmiturl,submitdata3) req6.add_header'User-Agent', 'Mozilla/5.0 Windows NT 6.1; WOW64) AppleWebKit/537.3 6 KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36 SE 2.X MetaSr 1.0') req6data=urllib.request.urlopenreq6).read).decode"utf-8","ignore") initdcurl="https://kyfw.12306.cn/otn/confirmPassenger/initDc" initdcdata =urllib.parse.urlencode{ "_json_att":"" }).encode'utf-8') req7 = urllib.request.Requestinitdcurl,initdcdata) req7.add_header'User-Agent', 'Mozilla/5.0 Windows NT 6.1; WOW64) AppleWebKit/537.3 6 KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36 SE 2.X MetaSr 1.0') req7data=urllib.request.urlopenreq7).read).decode"utf-8","ignore") train_no_pat="'train_no':'.*?)'" leftTicketStr_pat="'leftTicketStr':'.*?)'" fromStationTelecode_pat="from_station_telecode':'.*?)'" toStationTelecode_pat="'to_station_telecode':'.*?)'" train_location_pat="'train_location':'.*?)'" pattoken="var globalRepeatSubmitToken.*?'.*?)'" patkey="'key_check_isChange':'.*?)'" train_no_all=re.compiletrain_no_pat).findallreq7data) iflentrain_no_all)!=0): train_no=train_no_all[0] else: raise Exception"train_no获取失败") leftTicketStr_all=re.compileleftTicketStr_pat).findallreq7data) iflenleftTicketStr_all)!=0): leftTicketStr=leftTicketStr_all[0] else: raise Exception"leftTicketStr获取失败") fromStationTelecode_all=re.compilefromStationTelecode_pat).findallreq7data) iflenfromStationTelecode_all)!=0): fromStationTelecode=fromStationTelecode_all[0] else: raise Exception"fromStationTelecod获取失败") toStationTelecode_all=re.compiletoStationTelecode_pat).findallreq7data) iflentoStationTelecode_all)!=0): toStationTelecode=toStationTelecode_all[0] else: raise Exception"toStationTelecode获取失败") train_location_all=re.compiletrain_location_pat).findallreq7data) iflentrain_location_all)!=0): train_location=train_location_all[0] else: raise Exception"train_location获取失败") tokenall=re.compilepattoken).findallreq7data) iflentokenall)!=0): token=tokenall[0] else: raise Exception"Token获取失败") keyall=re.compilepatkey).findallreq7data) iflenkeyall)!=0): key=keyall[0] else: raise Exception"key_check_isChange获取失败") pattrain_location="'tour_flag':'dc','train_location':'.*?)'" train_locationall=re.compilepattrain_location).findallreq7data) iflentrain_locationall)!=0): train_location=train_locationall[0] else: raise Exception"train_location获取失败") getuserurl="https://kyfw.12306.cn/otn/confirmPassenger/getPassengerDTOs" getuserdata =urllib.parse.urlencode{ "REPEAT_SUBMIT_TOKEN":token, }).encode'utf-8') req8 = urllib.request.Requestgetuserurl,getuserdata) req8.add_header'User-Agent', 'Mozilla/5.0 Windows NT 6.1; WOW64) AppleWebKit/537.3 6 KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36 SE 2.X MetaSr 1.0') req8data=urllib.request.urlopenreq8).read).decode"utf-8","ignore") namepat='"passenger_name":".*?)"' idpat='"passenger_id_no":".*?)"' mobilepat='"mobile_no":".*?)"' countrypat='"country_code":".*?)"' nameall=re.compilenamepat).findallreq8data) idall=re.compileidpat).findallreq8data) mobileall=re.compilemobilepat).findallreq8data) countryall=re.compilecountrypat).findallreq8data) ifchooseno!="None"): pass else: for i in range0,lennameall)): print""+stri+1)+"位用户,姓名:"+strnameall[i])) chooseno=input"请选择要订票的用户的序号,如需选择多 位,可以自行修改一下代码") thisno=intchooseno)-1 iftrainzy[thiscode]==""): print"当前无票,继续监控…") continue checkOrderurl="https://kyfw.12306.cn/otn/confirmPassenger/checkOrderInfo" checkdata=urllib.parse.urlencode{ "cancel_flag":2, "bed_level_order_num":"000000000000000000000000000000", "passengerTicketStr":"M,0,1,"+strnameall[thisno])+",1,"+stridall[thisno])+", "+strmobileall[thisno])+",N", "oldPassengerStr":strnameall[thisno])+",1,"+stridall[thisno])+",1_", "tour_flag":"dc", "randCode":"", "whatsSelect":1, "_json_att":"", "REPEAT_SUBMIT_TOKEN":token, }).encode'utf-8') req9 = urllib.request.RequestcheckOrderurl,checkdata) req9.add_header'User-Agent', 'Mozilla/5.0 Windows NT 6.1; WOW64) AppleWebKit/537.36 KH TML, like Gecko) Chrome/38.0.2125.122 Safari/537.36 SE 2.X MetaSr 1.0') req9data=urllib.request.urlopenreq9).read).decode"utf-8","ignore") print"确认订单完成,即将进行下一步") getqueurl="https://kyfw.12306.cn/otn/confirmPassenger/getQueueCount" thisdatestr=date thisdate=datetime.datetime.strptimethisdatestr,"%Y-%m-%d").date) gmt='%a+%b+%d+%Y' thisgmtdate=thisdate.strftimegmt) leftstr2=leftTicketStr.replace"%","%25") getquedata="train_date="+strthisgmtdate)+"+00%3A00%3A00+GMT%2B0800&train_no="+train_no+"&sta tionTrainCode="+thiscode+"&seatType=M&fromStationTelecode="+fromStationTelecode+"&toStationTelecod e="+toStationTelecode+"&leftTicket="+leftstr2+"&purpose_codes=00&train_location="+train_location+"&_j son_att=&REPEAT_SUBMIT_TOKEN="+strtoken) getdata=getquedata.encode'utf-8') req10 = urllib.request.Requestgetqueurl,getdata) req10.add_header'User-Agent', 'Mozilla/5.0 Windows NT 6.1; WOW64) AppleWebKit/537.36 KHTM L, like Gecko) Chrome/38.0.2125.122 Safari/537.36 SE 2.X MetaSr 1.0') req10data=urllib.request.urlopenreq10).read).decode"utf-8","ignore") print"获取订单队列完成,即将进行下一步") confurl="https://kyfw.12306.cn/otn/confirmPassenger/confirmSingleForQueue" confdata2=urllib.parse.urlencode{ "passengerTicketStr":"M,0,1,"+strnameall[thisno])+",1,"+stridall[thisno])+", "+strmobileall[thisno])+",N", "oldPassengerStr":strnameall[thisno])+",1,"+stridall[thisno])+",1_", "randCode":"", "purpose_codes":"00", "key_check_isChange":key, "leftTicketStr":leftTicketStr, "train_location":train_location, "choose_seats":"", "seatDetailType":"000", "whatsSelect":"1", "roomType":"00", "dwAll":"N", "_json_att":"", "REPEAT_SUBMIT_TOKEN":token, }).encode'utf-8') req11 = urllib.request.Requestconfurl,confdata2) req11.add_header'User-Agent', 'Mozilla/5.0 Windows NT 6.1; WOW64) AppleWebKit/537.3 6 KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36 SE 2.X MetaSr 1.0') req11data=urllib.request.urlopenreq11).read).decode"utf-8","ignore") print"配置确认提交完成,即将进行下一步") time1=time.time) while True: time2=time.time) iftime2-time1)//60>5): print"获取orderid超时,正在进行新一次抢购") break getorderidurl="https://kyfw.12306.cn/otn/confirmPassenger/queryOrderWaitTime?random="+strinttime.time)*1000))+"&tourFlag=dc&_json_att=&REPEAT_SUBMIT_TOKEN="+strtoken) req12 = urllib.request.Requestgetorderidurl) req12.add_header'User-Agent', 'Mozilla/5.0 Windows NT 6.1; WOW64) AppleWebKit/537.36 KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36 SE 2.X MetaSr 1.0') req12data=urllib.request.urlopenreq12).read).decode"utf-8","ignore") patorderid='"orderId":".*?)"' orderidall=re.compilepatorderid).findallreq12data) iflenorderidall)==0): print"未获取到orderid,正在进行新一次的请求。") continue else: orderid=orderidall[0] break print"获取orderid完成,即将进行下一步") resulturl="https://kyfw.12306.cn/otn/confirmPassenger/resultOrderForDcQueue" resultdata="orderSequence_no="+orderid+"&_json_att=&REPEAT_SUBMIT_TOKEN="+strtoken) resultdata2=resultdata.encode'utf-8') req13 = urllib.request.Requestresulturl,resultdata2) req13.add_header'User-Agent', 'Mozilla/5.0 Windows NT 6.1; WOW64) AppleWebKit/537.36 KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36 SE 2.X MetaSr 1.0') req13data=urllib.request.urlopenreq13).read).decode"utf-8","ignore") print"请求结果完成,即将进行下一步") try: payurl="https://kyfw.12306.cn/otn//payOrder/init" paydata="_json_att=&REPEAT_SUBMIT_TOKEN="+strtoken) paydata2=paydata.encode'utf-8') req14 = urllib.request.Requestpayurl,paydata2) req14.add_header'User-Agent', 'Mozilla/5.0 Windows NT 6.1; WOW64) AppleWebKit/537.36 KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36 SE 2.X MetaSr 1.0') req14data=urllib.request.urlopenreq14).read).decode"utf-8","ignore") print"订单已经完成提交,您可以登录后台进行支付了。") break except Exception as err: break except Exception as err: printerr)

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注