利用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:
        orderId=orderWaitJson.get("data").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 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)#获取加密的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程序设计有所帮助。

(0)

相关推荐

  • python实现发送和获取手机短信验证码

    首先为大家分享python实现发送手机短信验证码后台方法,供大家参考,具体内容如下 1.生成4位数字验证码 def createPhoneCode(session): chars=['0','1','2','3','4','5','6','7','8','9'] x = random.choice(chars),random.choice(chars),random.choice(chars),random.choice(chars) verifyCode = "".join(x) s

  • Python爬虫模拟登录带验证码网站

    爬取网站时经常会遇到需要登录的问题,这是就需要用到模拟登录的相关方法.python提供了强大的url库,想做到这个并不难.这里以登录学校教务系统为例,做一个简单的例子. 首先得明白cookie的作用,cookie是某些网站为了辨别用户身份.进行session跟踪而储存在用户本地终端上的数据.因此我们需要用Cookielib模块来保持网站的cookie. 这个是要登陆的地址 http://202.115.80.153/ 和验证码地址 http://202.115.80.153/CheckCode.

  • Python脚本实现12306火车票查询系统

    最近我看到看到使用python实现火车票查询,我自己也实现了,感觉收获蛮多的,下面我就把每一步骤都详细给分享出来.(注意使用的是python3) 首先我将最终结果给展示出来: 在cmd命令行执行:python tickets.py -dk shanghai chengdu 20161007 > result.txt 意思是:查询 上海--成都 2016.10.07 的D和K开头的列车信息,并保存到 result.txt文件中:下面就是result.txt文件中的结果: 下面的将是实现步骤: 1.

  • python 图片验证码代码

    下面是一个实战项目的结果. 复制代码 代码如下: #coding: utf-8 import Image,ImageDraw,ImageFont,os,string,random,ImageFilter def initChars(): """ 允许的字符集合,初始集合为数字.大小写字母 usage: initChars() param: None return: list 返回允许的字符集和 for: picChecker类初始字符集合 todo: Nothing &quo

  • Python 用户登录验证的小例子

    复制代码 代码如下: #!/usr/bin/python#coding=gbk class User:    def __init__(self,username,password,age,sex):        self.username=username        self.password=password        self.age=age        self.sex=sex def tell(self):        print 'UserContext:Name:%s

  • Python爬虫爬验证码实现功能详解

    主要实现功能: - 登陆网页 - 动态等待网页加载 - 验证码下载 很早就有一个想法,就是自动按照脚本执行一个功能,节省大量的人力--个人比较懒.花了几天写了写,本着想完成验证码的识别,从根本上解决问题,只是难度太高,识别的准确率又太低,计划再次告一段落. 希望这次经历可以与大家进行分享和交流. Python打开浏览器 相比与自带的urllib2模块,操作比较麻烦,针对于一部分网页还需要对cookie进行保存,很不方便.于是,我这里使用的是Python2.7下的selenium模块进行网页上的操

  • python+pyqt实现12306图片验证效果

    本文实例为大家分享了python实现12306图片验证效果的具体代码,供大家参考,具体内容如下 思路:在鼠标点击位置加一个按钮,然后再按钮中的点击事件中写一个关闭事件. #coding:utf-8 from PyQt4.QtGui import * from PyQt4.QtCore import * from push_button import * from PIL import Image class Yanzheng(QWidget): def __init__(self,parent=

  • Python模拟登录12306的方法

    本文实例讲述了Python模拟登录12306的方法.分享给大家供大家参考. 具体实现方法如下: 复制代码 代码如下: #!/usr/bin/python # -*- coding: utf-8 -*-   import re; import sys; import cookielib; import urllib; import urllib2; import optparse; import json; import httplib2; reload(sys) sys.setdefaulten

  • Python验证码识别处理实例

    一.准备工作与代码实例 (1)安装PIL:下载后是一个exe,直接双击安装,它会自动安装到C:\Python27\Lib\site-packages中去, (2)pytesser:下载解压后直接放C:\Python27\Lib\site-packages(根据你安装的Python路径而不同),同时,新建一个pytheeer.pth,内容就写pytesser,注意这里的内容一定要和pytesser这个文件夹同名,意思就是pytesser文件夹,pytesser.pth,及内容都要一样! (3)Te

  • 使用Python神器对付12306变态验证码

    临近春节,我们小编带领大家用Python抢火车票! 首先我们需要splinter 安装: pip install splinter -i http://pypi.douban.com/simple –trusted-host pypi.douban.com 然后还需要一个浏览器的驱动,当然用chrome啦 下载地址: http://chromedriver.storage.googleapis.com/index.html?path=2.20/ 根据下载的自己的电脑系统选择下载包,我的windo

随机推荐