python自动12306抢票软件实现代码


Posted in Python onFebruary 24, 2018

昨天我发的是抓取的12306数据包,然后分析了一下,今天按照昨天的分析 用代码实现了,如果有需要的同学们可以看一下,实现的功能有,登录,验证码识别,自动查票,有余票点击预定, 差了最后一步提交订单。同学们可以自己研究一下。

import requests
import time
import dmpt
import re
import random
from copyheaders import headers_raw_to_dict

DEFAULT_HEADERS={
'Host':'kyfw.12306.cn',
'Connection':'keep-alive',
'Upgrade-Insecure-Requests':'1',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36',
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Referer':'https://kyfw.12306.cn/otn/index/init',
'Accept-Language':'zh-CN,zh;q=0.9',
}
def get_random():
  return str(random.random()) #生产一个18位的随机数
def get_13_time(): #一个十三位的时间戳
  return str(int(time.time()*1000))
class CN12306(object):
  def __init__(self):
    self.chufa='2018-02-03'
    self.s=requests.session()
    self.s.verify = False  # 忽略https 证书验证
  def get_init(self): #请求了一个首页
    url='https://kyfw.12306.cn/otn/login/init'
    r=self.s.get(url)
    print('首页获取成功,状态码:',r)

  def get_newpasscode(self): #这个页面不知道是干啥的,但是12306 请求了,咱们为了模仿的像一点也去请求
    url='https://kyfw.12306.cn/otn/resources/js/newpasscode/captcha_js.js?_={}'.format(get_13_time())
    r=self.s.get(url)
    print('newpasscode获取成功,状态码:',r)

  def get_auth_code(self): #获取验证码
    url='https://kyfw.12306.cn/passport/captcha/captcha-image?login_site=E&module=login&rand=sjrand&{}'.format(get_random())
    r=self.s.get(url)
    with open('auth_code.png', 'wb') as auth:
      auth.write(r.content)
      auth.flush()
      auth.close()
    return str(r) == '<Response [200]>'

  def analysis_auth_code(self): # 调用打码平台,返回验证码坐标
    dmt = dmpt.DamatuApi("打码平台帐号", "打码平台密码")
    analysis_auth = dmt.decode('auth_code.png', 287) # 上传打码
    analysis_auth = re.sub('\|', ',', analysis_auth)
    li = analysis_auth.split(',')
    for i in range(len(li)):
      if i % 2 == 0:
        pass
      else:
        li[i] = str(int(li[i]) - 30)
    analysis_auth = str(li)
    analysis_auth = re.sub("'", '', analysis_auth)
    analysis_auth = re.sub("\]", '', analysis_auth)
    analysis_auth = re.sub("\[", '', analysis_auth)
    analysis_auth = re.sub(" ", '', analysis_auth)
    print('验证码坐标', analysis_auth)
    self.analysis_auth= analysis_auth # 验证码坐标

  def auth_auth_code(self): #验证验证码是否正确提交方式post
    url='https://kyfw.12306.cn/passport/captcha/captcha-check'
    data={
      'answer':self.analysis_auth ,
      'login_site':'E',
      'rand':'sjrand',
    }
    r=self.s.post(url=url,data=data)
    print(r.text)
    if r.text == '''{"result_message":"验证码校验成功","result_code":"4"}''': #验证码校验成功
      return True
    else: #如果验证码校验失败
      print('验证码错误,刷新验证码,重新提交')
      if self.get_auth_code():  #获取验证码
        self.analysis_auth_code() #调用打码平台
        self.auth_auth_code() #重新校验验证码

  def login(self):
    url='https://kyfw.12306.cn/passport/web/login'
    data={
    'username' : '12306帐号',
    'password' : '12306密码',
    'appid' : 'otn',
    }
    r=self.s.post(url=url,data=data)
    self.uamtk=r.json()["uamtk"]

    print(r.text)

  def userLogin(self):
    url='https://kyfw.12306.cn/otn/login/userLogin'
    r=self.s.post(url=url)
    # print(r.text)
  def getjs(self):  #不知道是干啥的,但是也提交吧
    url='https://kyfw.12306.cn/otn/HttpZF/GetJS'
    r=self.s.get(url)
  def post_uamtk(self):
    url='https://kyfw.12306.cn/passport/web/auth/uamtk'
    data={ 'appid':'otn'}
    r=self.s.post(url=url,data=data,allow_redirects=False)
    self.newapptk=r.json()["newapptk"]
    r.encoding='utf-8'
    print(r.text)
  def post_uamauthclient(self):
    url='https://kyfw.12306.cn/otn/uamauthclient'
    data={
      'tk':self.newapptk
    }
    r=self.s.post(url=url,data=data)
    self.apptk = r.json()["apptk"]
    r.encoding='utf-8'
    print(r.text)
  def get_userLogin(self):
    url='https://kyfw.12306.cn/otn/login/userLogin'
    r=self.s.get(url)
    r.encoding='utf-8'
    # print(r.text)
  def get_leftTicket(self):
    url='https://kyfw.12306.cn/otn/leftTicket/init'
    r=self.s.get(url)
    r.encoding='utf-8'
    # print(r.text)
  def get_GetJS(self):
    url='https://kyfw.12306.cn/otn/HttpZF/GetJS'
    self.s.get(url)

  def get_qufzjql(self):
    url = 'https://kyfw.12306.cn/otn/dynamicJs/qufzjql'
    self.s.get(url)

  def get_queryZ(self):
    url='https://kyfw.12306.cn/otn/leftTicket/queryZ?leftTicketDTO.train_date={}&leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes={}'.format(self.chufa,'BJP','TBP','ADULT')
    r=self.s.get(url)
    r.encoding='utf-8'
    # print(r.text)
    cheliang=r.json()["data"]["result"]
    for i in cheliang:
      dandulist=str(i).split('|')
      if len(str(dandulist[0]))>=100:
        self.secretStr=dandulist[0]
        # secretStr = str(x[0])
        车次=str(dandulist[3])
        出发时间=str(dandulist[8])
        到达时间 = str(dandulist[9])
        历时=str(dandulist[10])
        软卧 = str(dandulist[23])
        硬卧=str(dandulist[28])
        print(i)
        print('可预订车次列表,','车次:',车次,'出发时间:', 出发时间,'到达时间:', 到达时间,'历时:', 历时,'软卧剩余: ',软卧,' 硬卧剩余: ',硬卧)
        if (软卧 != '' and 软卧 != '0' and 软卧 != '无' and 软卧 != '空') or (硬卧 != '' and 硬卧 != '0' and 硬卧 != '无' and 硬卧 != '空'):
          #执行下单操作
          self.post_submitOrderRequest()
          self.post_initDc()
          self.post_getPassengerDTOs()
          return False

      print('*****************************************************')
    return True


  # 点击预定下单
  def post_submitOrderRequest(self):
    url='https://kyfw.12306.cn/otn/leftTicket/submitOrderRequest'
    data={
      'secretStr':self.secretStr,
      'train_date':self.chufa, #出发时间
      'back_train_date':self.chufa ,#返回时间
      'tour_flag':'dc',
      'purpose_codes':'ADULT',
      'query_from_station_name':'北京',
      'query_to_station_name':'天津北',
      'undefined':''
       }
    r=self.s.post(url=url,data=data)
    print(r.text)
  def post_initDc(self):
    url='https://kyfw.12306.cn/otn/confirmPassenger/initDc'
    r=self.s.post(url)
    # r.text
    self.REPEAT_SUBMIT_TOKEN=re.findall("globalRepeatSubmitToken = '(.*?)';",r.text)[0]
  def post_getPassengerDTOs(self): #获取乘客信息
    url='https://kyfw.12306.cn/otn/confirmPassenger/getPassengerDTOs'
    data={
      'REPEAT_SUBMIT_TOKEN':self.REPEAT_SUBMIT_TOKEN,
      '_json_att':''
    }
    r=self.s.post(url=url,data=data)
    r.encoding='utf-8'
    print(r.text)

if __name__ == '__main__':
  print(get_random())
  cn=CN12306()
  cn.get_init()
  cn.get_newpasscode()
  if cn.get_auth_code():
    #如果验证码获取成功,就调用打码平台
    print('验证码获取成功')
    print('正在调用打码平台...')
    cn.analysis_auth_code()
    if cn.auth_auth_code(): #验证验证码是否正确
      cn.login()
      cn.userLogin()
      cn.getjs()
      cn.post_uamtk()
      cn.post_uamauthclient()
      cn.get_userLogin()
      cn.get_leftTicket()
      cn.get_GetJS()
      cn.get_qufzjql()

      while cn.get_queryZ():
        time.sleep(30)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
在Python中操作文件之seek()方法的使用教程
May 24 Python
详解Python如何获取列表(List)的中位数
Aug 12 Python
微信小程序跳一跳游戏 python脚本跳一跳刷高分技巧
Jan 04 Python
python numpy元素的区间查找方法
Nov 14 Python
Pyinstaller打包.py生成.exe的方法和报错总结
Apr 02 Python
pyqt5与matplotlib的完美结合实例
Jun 21 Python
用python求一个数组的和与平均值的实现方法
Jun 29 Python
pycharm配置当鼠标悬停时快速提示方法参数
Jul 31 Python
Python使用GitPython操作Git版本库的方法
Feb 29 Python
Python生成器next方法和send方法区别详解
May 30 Python
python 实现批量图片识别并翻译
Nov 02 Python
Python控制鼠标键盘代码实例
Dec 08 Python
浅谈Python中的zip()与*zip()函数详解
Feb 24 #Python
python模仿网页版微信发送消息功能
Feb 24 #Python
python2.7读取文件夹下所有文件名称及内容的方法
Feb 24 #Python
python opencv之分水岭算法示例
Feb 24 #Python
python3爬取各类天气信息
Feb 24 #Python
python opencv之SIFT算法示例
Feb 24 #Python
python3 破解 geetest(极验)的滑块验证码功能
Feb 24 #Python
You might like
php strlen mb_strlen计算中英文混排字符串长度
2009/07/10 PHP
php目录操作函数之获取目录与文件的类型
2010/12/29 PHP
PHP将两个关联数组合并函数提高函数效率
2014/03/18 PHP
PHP+Mysql无刷新问答评论系统(源码)
2016/12/20 PHP
PHP模型Model类封装数据库操作示例
2019/03/14 PHP
HTTP头隐藏PHP版本号实现过程解析
2020/12/09 PHP
JS 强制设为首页的代码
2009/01/31 Javascript
根据鼠标的位置动态的控制层的位置
2009/11/24 Javascript
Javascript四舍五入Math.round()与Math.pow()使用介绍
2013/12/27 Javascript
JavaScript构建自己的对象示例
2016/11/29 Javascript
JavaScript用JSONP跨域请求数据实例详解
2017/01/06 Javascript
JS实现最简单的冒泡排序算法
2017/02/15 Javascript
微信小程序 图片宽高自适应详解
2017/05/11 Javascript
微信小程序获取用户openId的实现方法
2017/05/23 Javascript
vue引用js文件的多种方式(推荐)
2018/05/17 Javascript
详解vue中axios的封装
2018/07/18 Javascript
解决React在安装antd之后出现的Can't resolve './locale'问题(推荐)
2020/05/03 Javascript
为什么str(float)在Python 3中比Python 2返回更多的数字
2018/10/16 Python
对python中数组的del,remove,pop区别详解
2018/11/07 Python
python3 selenium自动化 frame表单嵌套的切换方法
2019/08/23 Python
python正则表达式匹配IP代码实例
2019/12/28 Python
python GUI库图形界面开发之PyQt5时间控件QTimer详细使用方法与实例
2020/02/26 Python
解决json中ensure_ascii=False的问题
2020/04/03 Python
如何对python的字典进行排序
2020/06/19 Python
Python 读取位于包中的数据文件
2020/08/07 Python
selenium切换标签页解决get超时问题的完整代码
2020/08/30 Python
CSS3 伪类选择器 nth-child()说明
2010/07/10 HTML / CSS
html5跨域通讯之postMessage的用法总结
2013/11/07 HTML / CSS
经济学人订阅:The Economist
2018/07/19 全球购物
投标承诺书范本
2014/03/27 职场文书
电气工程及其自动化专业求职信
2014/06/23 职场文书
工作经常出错的检讨书
2014/09/13 职场文书
学习优秀党员杨宗兴先进事迹材料思想汇报
2014/09/14 职场文书
大学生自荐材料范文
2014/12/30 职场文书
离婚撤诉申请书范本
2015/05/18 职场文书
煤矿隐患排查制度
2015/08/05 职场文书