#!/usr/bin/env python
#-*- coding: utf-8 -*-
"""
通过splinter刷12306火车票
可以自动填充账号密码,同时,在登录时,也可以修改账号密码
然后手动识别验证码,并登陆,接下来的事情,交由脚本来做了,静静的等待抢票结果就好(刷票过程中,浏览器不可关闭)
"""
import re
from splinter.browser import Browser
from time import sleep
import time
import sys
import httplib2
from urllib import parse
import smtplib
import numpy as np
from email.mime.text import MIMEText
class BrushTicket(object):"""买票类及实现方法"""def __init__(self, user_name, password, passengers, from_time, from_station, to_station, number, seat_type):"""定义实例属性,初始化"""# 1206账号密码self.user_name = user_nameself.password = password# 乘客姓名self.passengers = passengers# 起始站和终点站self.from_station = from_stationself.to_station = to_station# 乘车日期self.from_time = from_time# 车次编号self.number = number.capitalize()# 座位类型所在td位置if seat_type == '商务座特等座':seat_type_index = 1seat_type_value = 9elif seat_type == '一等座':seat_type_index = 2seat_type_value = 'M'elif seat_type == '二等座':seat_type_index = 3seat_type_value = 0elif seat_type == '高级软卧':seat_type_index = 4seat_type_value = 6elif seat_type == '软卧':seat_type_index = 5seat_type_value = 4elif seat_type == '动卧':seat_type_index = 6seat_type_value = 'F'elif seat_type == '硬卧':seat_type_index = 7seat_type_value = 3elif seat_type == '软座':seat_type_index = 8seat_type_value = 2elif seat_type == '硬座':seat_type_index = 9seat_type_value = 1elif seat_type == '无座':seat_type_index = 10seat_type_value = 1elif seat_type == '其他':seat_type_index = 11seat_type_value = 1else:seat_type_index = 7seat_type_value = 3self.seat_type_index = seat_type_indexself.seat_type_value = seat_type_value# 主要页面网址self.login_url = 'https://kyfw.12306.cn/otn/login/init'self.init_my_url = 'https://kyfw.12306.cn/otn/view/index.html'self.ticket_url = 'https://kyfw.12306.cn/otn/leftTicket/init'# 浏览器驱动信息,驱动下载页:https://sites.google.com/a/chromium.org/chromedriver/downloadsself.driver_name = 'chrome'self.executable_path = r'H:\For personal use\PYTHON\file\chromedriver.exe'def do_login(self):"""登录功能实现,手动识别验证码进行登录"""self.driver.visit(self.login_url)sleep(1)self.driver.fill('loginUserDTO.user_name', self.user_name)self.driver.fill('userDTO.password', self.password)print('请输入验证码……')while True:if self.driver.url != self.init_my_url:sleep(1)else:breakdef start_brush(self):"""买票功能实现"""self.driver = Browser(driver_name=self.driver_name, executable_path=self.executable_path)# 浏览器窗口的大小self.driver.driver.set_window_size(1000, 900)self.do_login()self.driver.visit(self.ticket_url)try:print('开始刷票……')# 加载车票查询信息self.driver.cookies.add({"_jc_save_fromStation": self.from_station})self.driver.cookies.add({"_jc_save_toStation": self.to_station})self.driver.cookies.add({"_jc_save_fromDate": self.from_time})self.driver.reload()count = 0while self.driver.url.split('?')[0] == self.ticket_url:self.driver.find_by_text('查询').click()sleep(1)count += 1print('第%d次点击查询……' % count)try:car_no_location = self.driver.find_by_id("queryLeftTable")[0].find_by_text(self.number)[0]current_tr = car_no_location.find_by_xpath("./../../../../..")if current_tr.find_by_tag('td')[self.seat_type_index].text == '--':print('无此座位类型出售,已结束当前刷票,请重新开启!')sys.exit(1)elif current_tr.find_by_tag('td')[self.seat_type_index].text == '无':print('无票,继续尝试……')elif current_tr.find_by_tag('td')[self.seat_type_index].text == '候补':print('候补,继续尝试……')else:# 有票,尝试预订print('刷到票了(余票数:' + str(current_tr.find_by_tag('td')[self.seat_type_index].text) + '),开始尝试预订……')current_tr.find_by_css('td.no-br>a')[0].click()sleep(1)print('开始选择用户……')key_value = 1for p in self.passengers:# 选择用户self.driver.find_by_text(p).last.click()# 选择座位类型seat_select = self.driver.find_by_id("seatType_" + str(key_value))[0]seat_select.find_by_xpath("//option[@value='" + str(self.seat_type_value) + "']")[0].click()key_value += 1sleep(0.5)if p[-1] == ')':self.driver.find_by_id('dialog_xsertcj_ok').click()print('正在提交订单……')self.driver.find_by_id('submitOrder_id').click()sleep(0.5)# 查看放回结果是否正常submit_false_info = self.driver.find_by_id('orderResultInfo_id')[0].textif submit_false_info != '':print(submit_false_info)self.driver.find_by_id('qr_closeTranforDialog_id').click()sleep(0.2)self.driver.find_by_id('preStep_id').click()sleep(0.3)continueprint('正在确认订单……')self.driver.find_by_id('submitOrder_id').click()sleep(1)print('预订成功,请及时前往支付……')# 发送内容def mail_to(neirong, biaoti, geishei):text = neirongmsg = MIMEText(text, 'plain', 'utf-8')msg['subject'] = biaotimsg["From"] = geisheis = smtplib.SMTP(SMTPServer, 25)s.login(sender, passwd)s.sendmail(sender, sender, msg.as_string())s.quit()mail_to(neirong, biaoti, geishei)#self.driver.quit()except Exception as error_info:print(error_info)#self.driver.quit()breakexcept Exception as error_info:print(error_info)self.driver.quit()sys.exit(1)if __name__ == '__main__':# 城市cookie字典city_list = {'bj': '%u5317%u4EAC%2CBJP', # 北京'hd': '%u5929%u6D25%2CTJP', # 邯郸'nn': '%u5357%u5B81%2CNNZ', # 南宁'wh': '%u6B66%u6C49%2CWHN', # 武汉'cs': '%u957F%u6C99%2CCSQ', # 长沙'ty': '%u592A%u539F%2CTYV', # 太原'yc': '%u8FD0%u57CE%2CYNV', # 运城'gz': '%u5E7F%u5DDE%2CGZQ', # 广州'qhc': '%u6E05%u6CB3%u57CE%2CQYP' # 清河城}#邮件信息SMTPServer = "smtp.163.com"sender = "**********@163.com"passwd = "********"c = time.time()b = time.localtime(c)q = time.strftime("%Y-%m-%d %X", b)neirong = ("12306:" + q + " 搶到票了,轉進時間吧!")biaoti = ("一封信 " + q)geishei = sender# 从txt中获取信息with open(r'H:\For personal use\PYTHON\file\tickets.txt', 'r', encoding='utf-8', errors='ignore') as f:info_array = np.genfromtxt(f, dtype=str, delimiter=':')account = info_array[0][1]password = info_array[1][1]from_time = info_array[2][1]start = info_array[3][1]end = info_array[4][1]from_station = city_list[start]to_station = city_list[end]number = info_array[5][1]seat_type = info_array[6][1]passengers = info_array[7][1].split(",")#打印购票人信息print(account, password, passengers, from_time, from_station, to_station, number, seat_type)# 开始抢票ticket = BrushTicket(account, password, passengers, from_time, from_station, to_station, number, seat_type)ticket.start_brush()

When you don’t know what to do, just settle down and study!

python自动刷新12306抢票相关推荐

  1. python+selenium实现12306抢票

    python+selenium实现12306抢票 一.准备工作 1.要先下载相关的包,selenium.interval.最好使用国内清华源 pip install (which package) - ...

  2. python编程实践(3):python+selenium实现12306抢票脚本

    又到了一年一度的春运时节,抢个票? 1.设计思路 如果我们要买一张火车票,我们会怎么做?打开12306,登陆,输入出发地和目的地,选择出行日期,然后点击查询,有余票的话就下单购买,没有票就点刷新或者等 ...

  3. Python 实现的12306抢票脚本

    Python12306抢票脚本 本脚本使用一个类来实现所有代码,大体上分为以下几个模块及其步骤: - 初始化对象属性(在抢票前进行的属性初始化,包括初始化浏览器模拟对象,个人信息等). - 建立模拟浏 ...

  4. Python版实现12306抢票功能,真的能帮你抢到春运回家的票吗?

    背景 每逢佳节倍思亲,年关将近,思乡的情绪是不是愈发强烈了,筒子们是不是又要准备开始抢票了,还是在找黄牛吗?但是,今年在考虑是否能抢到票以外,还需要考虑是否能回得去,没错,因为疫情,需要全国人民同心协 ...

  5. 【Python脚本】Python自动大麦网抢票,准点原价秒杀演唱会门票,拒绝黄牛交易!从我做起!!!1

    文章目录 前言 一.分析购票过程 二.Selenium 模拟浏览器操作 三.逆向工程:抢票接口 总结 前言 你是否错过了周杰伦的票,最近又没抢到五月天的票,不要太难过,今晚有张学友的票,后天还有张杰的 ...

  6. python GUI+爬虫——12306抢票软件(1)

    使用python 的GUI 和爬虫等功能自己构造一个12306的抢票软件. 该课程来自网易云课堂的撩课学院,付费课程.地址:网易云课堂搜索以下内容就可找到 我跟着学,不一定最后能成功.先试试,想要成功 ...

  7. Python实例 一 12306抢票(二) 下单

    第二篇 刷票与下单 原文地址:http://www.tnblog.net/cz/article/details/241 解决"url":"/leftTicket/init ...

  8. 用Python自动刷新抢12306火车票(附源码)

    專 欄 ❈ 作者:marvin,互联网从业者,现居上海张江 ❈ 一年一度的春运又来了,今年我自己写了个抢票脚本.使用Python+Splinter自动刷新抢票,可以成功抢到.(依赖自己的网络环境太厉害 ...

  9. python12306自动抢票为什么进入个人中心,python自动登录12306并自动点击验证码完成登录的实现源代码...

    以下代码可自动登录12306 - 包括输入用户名密码以及自动识别验证码并点击验证码登陆.该源码需要稍作修改: 把  username.send_keys('xxxxxxx')  中的  xxxxxx ...

最新文章

  1. 同是产品经理,为什么几年后会差距这么大?
  2. caffe之特征图可视化及特征提取
  3. super构造方法为什么给子类赋值_【Java学习 | Javase】super
  4. 【BZOJ2791】[Poi2012]Rendezvous 倍增
  5. 【uoj#37/bzoj3812】[清华集训2014]主旋律 状压dp+容斥原理
  6. JS判断文本框中只能输入数字和小数点
  7. 开发中常见的@NotNull,@NotBlank,@NotEmpty注解的区别
  8. 如何删除Smartphone手机与Office同步后的重复项,如联系人、日程等。Keyword:office,Outlook,删除,重复项目...
  9. oracle10g配置失败,求解决装oracle10g的时候EM配置失败问题
  10. ANSYS_APDL——实例001-模态分析
  11. 计算机学院王乐君,自动化学院2019年研究生科技报告会安排-中国地质大学(武汉)自动化学院...
  12. 鲁大师2022年Q1季度电动车报告:市场不断细分,产品白刃战开启
  13. 缺陷管理工具--mantis使用过程
  14. macOS Ventura 13.1 (22C65) 正式版发布,ISO、IPSW、PKG 下载
  15. python多个函数_请教:一个类中可以定义多个同名函数?
  16. 金融业大数据风控方式
  17. 【ELM分类】基于matlab遗传算法优化ELM神经网络数据分类【含Matlab源码 2138期】
  18. 蚂蚁金服战略入股润和软件,竟然是为了它?
  19. PyCharm的使用
  20. 都知道面向对象了,那么面向切面呢!通俗易懂带你走进面向切面编程!

热门文章

  1. IEEE 2017 STAM16 阅读笔记
  2. SteamVR 2.x UGUI交互系统(7)
  3. CSS简单实现圣杯布局和双飞翼布局
  4. 【Python】 plt.savefig保存图片时一片空白
  5. 流媒体服务器(1)—— 一个非常好用云转码流媒体平台
  6. Python-入门学习
  7. html5如何让多张图片重叠,HTML5图片层叠
  8. 树莓派连接yl-69土壤湿度传感器
  9. 苹果ID不能登陆:The action could not be completed. Try again
  10. typec扩展坞hdmi没反应_手机\笔记本使用Type-c扩展坞的问题解析