广告
返回顶部
首页 > 资讯 > 后端开发 > Python >利用python代码写的12306订票代码
  • 147
分享到

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

代码订票python 2022-06-04 19:06:38 147人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

本文实例讲述了python代码写的12306订票代码,分享给大家供大家参考。 具体实现方法如下: import datetime import JSON import re import sys imp

本文实例讲述了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("/file/imgs/upload/202206/04/fs15i0lawis.html","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("/file/imgs/upload/202206/04/2j4mtp22wy2.html","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程序设计有所帮助。

--结束END--

本文标题: 利用python代码写的12306订票代码

本文链接: https://www.lsjlt.com/news/15570.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 利用python代码写的12306订票代码
    本文实例讲述了python代码写的12306订票代码,分享给大家供大家参考。 具体实现方法如下: import datetime import json import re import sys imp...
    99+
    2022-06-04
    代码 订票 python
  • Java实现火车票预订系统的代码怎么写
    本文小编为大家详细介绍“Java实现火车票预订系统的代码怎么写”,内容详细,步骤清晰,细节处理妥当,希望这篇“Java实现火车票预订系统的代码怎么写”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。 一、项...
    99+
    2023-06-29
  • 用vim写python代码
    适用环境:linux系统,windows的没有研究过,可能路径不同如何使用。git clone https://github.com/itnihao/vimrc-python.git cd vimrc-python mv ~/.vimrc ...
    99+
    2023-01-31
    代码 vim python
  • 利用Python探测附近WIFI密码的代码怎么写
    利用Python探测附近WIFI密码的代码怎么写,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。前言下面将学习下如何通过 Python 脚本实现 WIFI 密码的暴力破解,从而实...
    99+
    2023-06-28
  • C语言实现飞机订票系统的完整代码
    目录题目总体设计和需求分析设计目的总体设计和功能结构体设计机票信息结构体主函数的设计各功能代码的实现前置添加机票查找机票信息修改机票信息显示机票信息推荐机票信息订票退票保存信息显示时...
    99+
    2022-11-13
  • python的皮卡丘如何写代码,用python皮卡丘的代码
    大家好,小编为大家解答python的皮卡丘如何写代码的问题。很多人还不知道python皮卡丘字符打印代码,现在让我们一起来看看吧! 一、哆啦A梦 由于代码过长,这里仅显示部分代码: from turtle import \...
    99+
    2023-10-12
    python
  • 怎么写好的Python代码
    本篇内容介绍了“怎么写好的Python代码”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!所谓 pythonic,我觉得包含两方面:一是代码的...
    99+
    2023-06-02
  • 用Python写冒泡排序代码
    python代码实现冒泡排序代码其实很简单,具体代码如下所示: 代码Code highlighting produced by Actipro CodeHighlighter (freeware)htt...
    99+
    2022-06-04
    代码 Python
  • 利用ChatGPT编写一段嵌入式代码
    目录1、ChatGPT介绍2、注册账号3、体验ChatGPT1、ChatGPT介绍 ChatGPT: Optimizing Language Models for Dialogue,...
    99+
    2023-02-15
    ChatGPT编写嵌入式代码 ChatGPT嵌入式代码 ChatGPT代码
  • 利用cython将python转为c代码
    1. 安装cython 2. cython test.py --embed 3. gcc `python-config --cflags` `python-config --ldflags` test.c -o test ...
    99+
    2023-01-31
    代码 cython python
  • 利用Python探测附近WIFI密码的详细代码
    前言 本文将记录学习下如何通过 Python 脚本实现 WIFI 密码的暴力破解,从而实现免费蹭网。 无图形界面 先来看看没有图形界面版的爆破脚本。 WIFI爆破 import py...
    99+
    2022-11-13
  • python去水印的代码怎么写
    去除水印的代码取决于水印是如何添加到图像中的。以下是一种常见的方法,使用OpenCV库和图像处理技术来去除简单的文本水印:```py...
    99+
    2023-09-18
    python
  • python操作excel的代码怎么写
    本篇内容主要讲解“python操作excel的代码怎么写”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“python操作excel的代码怎么写”吧!from&nb...
    99+
    2022-10-19
  • 如何进行Python代码的编写
    这篇文章将为大家详细讲解有关如何进行Python代码的编写,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。Python 调用在日常工作中还是非常实用的,只需要Python函数就可以了,如果对P...
    99+
    2023-06-17
  • 爬取某网站写的python代码
        代码如下:import requestsfrom pyquery import PyQueryimport reimport osi...
    99+
    2023-06-04
  • 利用Unity制作特写镜头的示例代码
    目录类似这种效果1.首先制作上下两层黑边2.摄像头聚焦的效果类似这种效果 黑边的大小可以自行调整 这里为了方便直接用两个Button绑定了方法,有需要自行调用方法 1.首先制作上...
    99+
    2022-11-13
  • 怎么用一行Python代码识别增值税发票
    今天小编给大家分享一下怎么用一行Python代码识别增值税发票的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。识别发票录入发票...
    99+
    2023-07-05
  • 用Python写漏洞验证脚本的代码
    小白尝试写任意文件读取poc 我是一个小白,完全不懂Python,但是Python在渗透中往往是一个重要的角色。有一个CSDN百万大佬写了这样一句话,不会编程的渗透都是耍流氓。我虽然...
    99+
    2022-11-13
  • 使用python发邮件的代码怎么写
    这篇文章主要介绍了使用python发邮件的代码怎么写的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇使用python发邮件的代码怎么写文章都会有所收获,下面我们一起来看看吧。相关...
    99+
    2022-10-19
  • python调用api接口的代码怎么写
    你可以使用`requests`库来调用API接口,下面是一个简单的示例代码:```pythonimport requestsurl ...
    99+
    2023-08-30
    python
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作