利用python代码写的12306订票代码

本文实例讲述了python代码写的12306订票代码,分享给大家供大家参考。

具体实现方法如下:

import datetime
import json
import re
import sys
import time
import image
import pyv8
import requests
import tools.email_helper as emailhelper
reload(sys)
sys.setdefaultencoding(‘utf-8’) # @undefinedvariable
reqsingle = requests.session()
attcheci=[“g655″,”g6741″,”g67″,”g491”] #关注的车次
datelist=[“2015-02-18″] #关注的日期
username=”12306登录用户名”
password=”登录密码”
#这个是需要手动提交订单后f12自己找的,挨个post请求去找,参数名为:oldpassengerstr 格式如下
oldpassengerstr=”姓名,1,130434199802036011,1_姓名2,1,130434199204238069,1_”
#这个是需要手动提交订单后f12自己找的,挨个post请求去找,参数名为:passengerticketstr 格式如下
passengerticketstr=”o,0,1,姓名,1,130434199802036011,13683456789,n_o,0,1,姓名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[“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
#初始化订票
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(“订票出现错误”)
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()
#验证码
#开始做验证码
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(“请输入登录验证码:”)
#验证验证码
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 “验证码输入正确!”
#检查票
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”:passengerticketstr,
“randcode”:randcode,
“tour_flag”:”dc”
})
checkorderinfojson=checkorderinforeq.json()
if checkorderinfojson.get(“status”)==false or checkorderinfojson.get(“httpstatus”)!=200:
raise exception(“检查票出现错误”)
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”:””,
“fromstationtelecode”: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(“获取队列错误”)
#确认队列
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”:leftticket,
“oldpassengerstr”:oldpassengerstr,
“passengerticketstr”:passengerticketstr,
“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异常”)
if singleforqueuejson.get(“data”) is none or singleforqueuejson.get(“data”).get(“submitstatus”)==false:
raise exception(“confirmsingleforqueue异常”)
#等待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:
orderdata”).get(“orderid”)
break
pass
pass
#进入队列
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 “订票成功”
pass
else:
print dcqueuejson.content
print “订票失败”
pass
#https://kyfw.12306.cn/otn/confirmpassenger/resultorderfordcqueue
pass
#检查是否登录
def checkislogin():
checkreq= reqsingle.post(“https://kyfw.12306.cn/otn/login/checkuser”, data={“_json_att”:””},headers=header)
print u”检查是否登录”+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
#提取js加密内容后的key和value
def extractkey(htmlcontent,headerxx):
loginmatch=re.search(r’《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)#获取加密的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
#登录操作
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(“请输入登录验证码:”)
#验证验证码
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”).get(“result”)==”1″:
break;
pass
print “验证码输入正确!”
#开始登陆
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”)==200:
if loginresjson.get(“data”) is not none and loginresjson.get(“data”).get(“logincheck”)==”y”:
print “登录成功”
else:
raise exception(loginres.content)
else:
login()
pass
def 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 exception:
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 checi 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!=”无” and (yznum==”有” or int(yznum)>=2):
#发邮件
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”个硬座”
# print body
# mailer=emailhelper.email_helper(“smtp.qq.com”, “fd”, “fss”, “qq.com”,”plain”)
# mailer.send(“630419595@qq.com”, u”有火车票了”,body)
# raise exception(“有票了”)
pass
print traincode+yznum
pass
pass
pass
if __name__ == ‘__main__’:
# login()
# if checkislogin():
# print “登录成功”
#
# orderticket(“北京西”,”邯郸东”,”2015-01-14″,”mjaxns0wms0xncmwmcnhnjczmsmwmjoxnsmwnzownsmyndawmec2nzmxmdujqlhqi0hqucmwotoymcpljjfkuqzopb8j6ykv6yo45licizaxiza2i08wmdawmda4mthnmdawmdawmtewotawmdawmdayninqmimxnde5mdg2otu2mta0izi5nei0qky0qtu2ode2rdu1mze5rkrcrkveqzq3mzk2mueyruewoem0muvcmjzgmdc3ruuynzc0″)
# exit()
login()
if checkislogin():
print “登录成功”
while true:
checkcount=0
for dt in datelist:
checkticket(dt)
time.sleep(2)
checkcount+=1
if checkcount%10==0:
if checkislogin():
print “成功状态”
else:
print “被踢了”
pass
pass

大家抢到回家过年的车票了吗?

希望本文所述对大家的python程序设计有所帮助。

Posted in 未分类

发表评论