利用Python3.6的Splinter模块模拟浏览器刷12306火车票

2023-10-17 01:50

本文主要是介绍利用Python3.6的Splinter模块模拟浏览器刷12306火车票,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文件结构

qiangpiao.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-"""
通过splinter刷12306火车票
可以自动填充账号密码,同时,在登录时,也可以修改账号密码
然后手动识别验证码,并登陆,接下来的事情,交由脚本来做了,静静的等待抢票结果就好(刷票过程中,浏览器不可关闭)
author: cuizy
time: 2018-05-30
"""import re
from splinter.browser import Browser
from time import sleep
import sys
import httplib2
from urllib import parse
import smtplib
from email.mime.text import MIMETextclass BrushTicket(object):"""买票类及实现方法"""def __init__(self, user_name, password, passengers, from_time, from_station, to_station, number, seat_type, receiver_mobile, receiver_email):"""定义实例属性,初始化"""# 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.receiver_mobile = receiver_mobileself.receiver_email = receiver_email# 主要页面网址self.login_url = 'https://kyfw.12306.cn/otn/login/init'self.init_my_url = 'https://kyfw.12306.cn/otn/index/initMy12306'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 = 'C:\\Users\cuizy\AppData\Local\Programs\Python\Python36\Scripts\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(900, 700)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)[1]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('无票,继续尝试……')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)key_value = 1for p in self.passengers:# 选择用户print('开始选择用户……')self.driver.find_by_text(p).last.click()# 选择座位类型print('开始选择席别……')if self.seat_type_value != 0: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(2)# 查看放回结果是否正常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('qr_submit_id').click()print('预订成功,请及时前往支付……')# 发送通知信息self.send_mail(self.receiver_email, '恭喜您,抢到票了,请及时前往12306支付订单!')self.send_sms(self.receiver_mobile, '您的验证码是:8888。请不要把验证码泄露给其他人。')except Exception as error_info:print(error_info)except Exception as error_info:print(error_info)def send_sms(self, mobile, sms_info):"""发送手机通知短信,用的是-互亿无线-的测试短信"""host = "106.ihuyi.com"sms_send_uri = "/webservice/sms.php?method=Submit"account = "C59782899"pass_word = "19d4d9c0796532c7328e8b82e2812655"params = parse.urlencode({'account': account, 'password': pass_word, 'content': sms_info, 'mobile': mobile, 'format': 'json'})headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}conn = httplib2.HTTPConnectionWithTimeout(host, port=80, timeout=30)conn.request("POST", sms_send_uri, params, headers)response = conn.getresponse()response_str = response.read()conn.close()return response_strdef send_mail(self, receiver_address, content):"""发送邮件通知"""# 连接邮箱服务器信息host = 'smtp.163.com'port = 25sender = 'gxcuizy@163.com'  # 你的发件邮箱号码pwd = 'CUIzy9118'  # 不是登陆密码,是客户端授权密码# 发件信息receiver = receiver_addressbody = '<h2>温馨提醒:</h2><p>' + content + '</p>'msg = MIMEText(body, 'html', _charset="utf-8")msg['subject'] = '抢票成功通知!'msg['from'] = sendermsg['to'] = receivers = smtplib.SMTP(host, port)# 开始登陆邮箱,并发送邮件s.login(sender, pwd)s.sendmail(sender, receiver, msg.as_string())if __name__ == '__main__':# 12306用户名user_name = input('请输入12306用户名:')while user_name == '':user_name = input('12306用户名不能为空,请重新输入:')# 12306登陆密码password = input('请输入12306登陆密码:')while password == '':password = input('12306登陆密码不能为空,请重新输入:')# 乘客姓名passengers_input = input('请输入乘车人姓名,多人用英文逗号“,”连接,(例如单人“张三”或者多人“张三,李四”):')passengers = passengers_input.split(",")while passengers_input == '' or len(passengers) > 4:print('乘车人最少1位,最多4位!')passengers_input = input('请重新输入乘车人姓名,多人用英文逗号“,”连接,(例如单人“张三”或者多人“张三,李四”):')passengers = passengers_input.split(",")# 乘车日期from_time = input('请输入乘车日期(例如“2018-08-08”):')date_pattern = re.compile(r'^\d{4}-\d{2}-\d{2}$')while from_time == '' or re.findall(date_pattern, from_time) == []:from_time = input('乘车日期不能为空或者时间格式不正确,请重新输入:')# 城市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',  # 运城'gzn': '%u5E7F%u5DDE%u5357%2CIZQ',  # 广州南'wzn': '%u68A7%u5DDE%u5357%2CWBZ',  # 梧州南}# 出发站from_input = input('请输入出发站,只需要输入首字母就行(例如北京“bj”):')while from_input not in city_list.keys():from_input = input('出发站不能为空或不支持当前出发站(如有需要,请联系管理员!),请重新输入:')from_station = city_list[from_input]# 终点站to_input = input('请输入终点站,只需要输入首字母就行(例如北京“bj”):')while to_input not in city_list.keys():to_input = input('终点站不能为空或不支持当前终点站(如有需要,请联系管理员!),请重新输入:')to_station = city_list[to_input]# 车次编号number = input('请输入车次号(例如“G110”):')while number == '':number = input('车次号不能为空,请重新输入:')# 座位类型seat_type = input('请输入座位类型(例如“软卧”):')while seat_type == '':seat_type = input('座位类型不能为空,请重新输入:')# 抢票成功,通知该手机号码receiver_mobile = input('请预留一个手机号码,方便抢到票后进行通知(例如:18888888888):')mobile_pattern = re.compile(r'^1{1}\d{10}$')while receiver_mobile == '' or re.findall(mobile_pattern, receiver_mobile) == []:receiver_mobile = input('预留手机号码不能为空或者格式不正确,请重新输入:')receiver_email = input('请预留一个邮箱,方便抢到票后进行通知(例如:test@163.com):')while receiver_email == '':receiver_email = input('预留邮箱不能为空,请重新输入:')# 开始抢票ticket = BrushTicket(user_name, password, passengers, from_time, from_station, to_station, number, seat_type, receiver_mobile, receiver_email)ticket.start_brush()

 new_qiangpiao.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-"""
通过splinter刷12306火车票
进入登陆页面,可以选择扫码登陆或者账号密码登陆
登陆成功后,接下来的事情,交由脚本来做了,静静的等待抢票结果就好(刷票过程中,浏览器不可关闭)
抢票成功,会进行手机短信和邮件的通知
author: cuizy
time: 2018-11-21
"""import re
from splinter.browser import Browser
from time import sleep
import sys
import httplib2
from urllib import parse
import smtplib
from email.mime.text import MIMEText
import timeclass BrushTicket(object):"""买票类及实现方法"""def __init__(self, passengers, from_time, from_station, to_station, number, seat_type, receiver_mobile,receiver_email):"""定义实例属性,初始化"""# 乘客姓名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.receiver_mobile = receiver_mobileself.receiver_email = receiver_email# 新版12306官网主要页面网址self.login_url = 'https://kyfw.12306.cn/otn/resources/login.html'self.init_my_url = 'https://kyfw.12306.cn/otn/view/index.html'self.ticket_url = 'https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=dc'# 浏览器驱动信息,驱动下载页:https://sites.google.com/a/chromium.org/chromedriver/downloadsself.driver_name = 'chrome'self.driver = Browser(driver_name=self.driver_name)def do_login(self):"""登录功能实现,手动识别验证码进行登录"""self.driver.visit(self.login_url)sleep(1)# 选择登陆方式登陆print('请扫码登陆或者账号登陆……')while True:if self.driver.url != self.init_my_url:sleep(1)else:breakdef start_brush(self):"""买票功能实现"""# 浏览器窗口最大化self.driver.driver.maximize_window()# 登陆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 == self.ticket_url:try:self.driver.find_by_text('查询').click()except Exception as error_info:print(error_info)sleep(1)continuesleep(0.5)count += 1local_date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())print('第%d次点击查询……[%s]' % (count, local_date))try:current_tr = self.driver.find_by_xpath('//tr[@datatran="' + self.number + '"]/preceding-sibling::tr[1]')if current_tr: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('无票,继续尝试……')sleep(1)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)key_value = 1for p in self.passengers:if '()' in p:p = p[:-1] + '学生' + p[-1:]# 选择用户print('开始选择用户……')self.driver.find_by_text(p).last.click()# 选择座位类型print('开始选择席别……')if self.seat_type_value != 0:self.driver.find_by_xpath("//select[@id='seatType_" + str(key_value) + "']/option[@value='" + str(self.seat_type_value) + "']").first.click()key_value += 1sleep(0.2)if p[-1] == ')':self.driver.find_by_id('dialog_xsertcj_ok').click()print('正在提交订单……')self.driver.find_by_id('submitOrder_id').click()sleep(2)# 查看放回结果是否正常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('qr_submit_id').click()print('预订成功,请及时前往支付……')# 发送通知信息self.send_mail(self.receiver_email, '恭喜您,抢到票了,请及时前往12306支付订单!')self.send_sms(self.receiver_mobile, '您的验证码是:8888。请不要把验证码泄露给其他人。')else:print('不存在当前车次【%s】,已结束当前刷票,请重新开启!' % self.number)sys.exit(1)except Exception as error_info:print(error_info)# 跳转到抢票页面self.driver.visit(self.ticket_url)except Exception as error_info:print(error_info)def send_sms(self, mobile, sms_info):"""发送手机通知短信,用的是-互亿无线-的测试短信"""host = "106.ihuyi.com"sms_send_uri = "/webservice/sms.php?method=Submit"account = "C59782899"pass_word = "19d4d9c0796532c7328e8b82e2812655"params = parse.urlencode({'account': account, 'password': pass_word, 'content': sms_info, 'mobile': mobile, 'format': 'json'})headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}conn = httplib2.HTTPConnectionWithTimeout(host, port=80, timeout=30)conn.request("POST", sms_send_uri, params, headers)response = conn.getresponse()response_str = response.read()conn.close()return response_strdef send_mail(self, receiver_address, content):"""发送邮件通知"""# 连接邮箱服务器信息host = 'smtp.163.com'port = 25sender = 'gxcuizy@163.com'  # 你的发件邮箱号码pwd = '******'  # 不是登陆密码,是客户端授权密码# 发件信息receiver = receiver_addressbody = '<h2>温馨提醒:</h2><p>' + content + '</p>'msg = MIMEText(body, 'html', _charset="utf-8")msg['subject'] = '抢票成功通知!'msg['from'] = sendermsg['to'] = receivers = smtplib.SMTP(host, port)# 开始登陆邮箱,并发送邮件s.login(sender, pwd)s.sendmail(sender, receiver, msg.as_string())if __name__ == '__main__':# 乘客姓名passengers_input = input('请输入乘车人姓名,多人用英文逗号“,”连接,(例如单人“张三”或者多人“张三,李四”,如果学生的话输入“王五()”):')passengers = passengers_input.split(",")while passengers_input == '' or len(passengers) > 4:print('乘车人最少1位,最多4位!')passengers_input = input('请重新输入乘车人姓名,多人用英文逗号“,”连接,(例如单人“张三”或者多人“张三,李四”):')passengers = passengers_input.split(",")# 乘车日期from_time = input('请输入乘车日期(例如“2018-08-08”):')date_pattern = re.compile(r'^\d{4}-\d{2}-\d{2}$')while from_time == '' or re.findall(date_pattern, from_time) == []:from_time = input('乘车日期不能为空或者时间格式不正确,请重新输入:')# 城市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',  # 运城'gzn': '%u5E7F%u5DDE%u5357%2CIZQ',  # 广州南'wzn': '%u68A7%u5DDE%u5357%2CWBZ',  # 梧州南}# 出发站from_input = input('请输入出发站,只需要输入首字母就行(例如北京“bj”):')while from_input not in city_list.keys():from_input = input('出发站不能为空或不支持当前出发站(如有需要,请联系管理员!),请重新输入:')from_station = city_list[from_input]# 终点站to_input = input('请输入终点站,只需要输入首字母就行(例如北京“bj”):')while to_input not in city_list.keys():to_input = input('终点站不能为空或不支持当前终点站(如有需要,请联系管理员!),请重新输入:')to_station = city_list[to_input]# 车次编号number = input('请输入车次号(例如“G110”):')while number == '':number = input('车次号不能为空,请重新输入:')# 座位类型seat_type = input('请输入座位类型(例如“软卧”):')while seat_type == '':seat_type = input('座位类型不能为空,请重新输入:')# 抢票成功,通知该手机号码receiver_mobile = input('请预留一个手机号码,方便抢到票后进行通知(例如:18888888888):')mobile_pattern = re.compile(r'^1{1}\d{10}$')while receiver_mobile == '' or re.findall(mobile_pattern, receiver_mobile) == []:receiver_mobile = input('预留手机号码不能为空或者格式不正确,请重新输入:')receiver_email = input('请预留一个邮箱,方便抢到票后进行通知(例如:test@163.com):')while receiver_email == '':receiver_email = input('预留邮箱不能为空,请重新输入:')# 开始抢票ticket = BrushTicket(passengers, from_time, from_station, to_station, number, seat_type, receiver_mobile,receiver_email)ticket.start_brush()

new_qiangpiao_by_no.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-"""
通过splinter刷12306火车票(多个车次查询)
进入登陆页面,可以选择扫码登陆或者账号密码登陆
登陆成功后,接下来的事情,交由脚本来做了,静静的等待抢票结果就好(刷票过程中,浏览器不可关闭)
抢票成功,会进行手机短信和邮件的通知
author: cuizy
time: 2018-12-28
"""import re
from splinter.browser import Browser
from time import sleep
import sys
import httplib2
from urllib import parse
import smtplib
from email.mime.text import MIMEText
import timeclass BrushTicket(object):"""买票类及实现方法"""def __init__(self, passengers, from_time, from_station, to_station, numbers, seat_type, receiver_mobile,receiver_email):"""定义实例属性,初始化"""# 乘客姓名self.passengers = passengers# 起始站和终点站self.from_station = from_stationself.to_station = to_station# 车次self.numbers = list(map(lambda number: number.capitalize(),numbers))# 乘车日期self.from_time = from_time# 座位类型所在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.receiver_mobile = receiver_mobileself.receiver_email = receiver_email# 新版12306官网主要页面网址self.login_url = 'https://kyfw.12306.cn/otn/resources/login.html'self.init_my_url = 'https://kyfw.12306.cn/otn/view/index.html'self.ticket_url = 'https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=dc'# 浏览器驱动信息,驱动下载页:https://sites.google.com/a/chromium.org/chromedriver/downloadsself.driver_name = 'chrome'self.driver = Browser(driver_name=self.driver_name)def do_login(self):"""登录功能实现,手动识别验证码进行登录"""self.driver.visit(self.login_url)sleep(1)# 选择登陆方式登陆print('请扫码登陆或者账号登陆……')while True:if self.driver.url != self.init_my_url:sleep(1)else:breakdef start_brush(self):"""买票功能实现"""# 浏览器窗口最大化self.driver.driver.maximize_window()# 登陆self.do_login()# 跳转到抢票页面self.driver.visit(self.ticket_url)sleep(1)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 == self.ticket_url:try:self.driver.find_by_text('查询').click()except Exception as error_info:print(error_info)sleep(1)continuesleep(0.5)count += 1local_date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())print('第%d次点击查询……[%s]' % (count, local_date))try:start_list = self.driver.find_by_css('.start-t')for start_time in start_list:current_time = start_time.textcurrent_tr = start_time.find_by_xpath('ancestor::tr')if current_tr:car_no = current_tr.find_by_css('.number').textif car_no in self.numbers:if current_tr.find_by_tag('td')[self.seat_type_index].text == '--':print('%s无此座位类型出售……' % (car_no + '(' + current_time + ')',))sleep(0.2)elif current_tr.find_by_tag('td')[self.seat_type_index].text == '无':print('%s无票……' % (car_no + '(' + current_time + ')',))sleep(0.2)else:# 有票,尝试预订print(car_no + '(' + current_time + ')刷到票了(余票数:' + str(current_tr.find_by_tag('td')[self.seat_type_index].text) + '),开始尝试预订……')current_tr.find_by_css('td.no-br>a')[0].click()sleep(0.5)key_value = 1for p in self.passengers:if '()' in p:p = p[:-1] + '学生' + p[-1:]# 选择用户print('开始选择用户……')self.driver.find_by_text(p).last.click()# 选择座位类型print('开始选择席别……')if self.seat_type_value != 0:self.driver.find_by_xpath("//select[@id='seatType_" + str(key_value) + "']/option[@value='" + str(self.seat_type_value) + "']").first.click()key_value += 1sleep(0.2)if p[-1] == ')':self.driver.find_by_id('dialog_xsertcj_ok').click()print('正在提交订单……')self.driver.find_by_id('submitOrder_id').click()sleep(2)# 查看放回结果是否正常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('qr_submit_id').click()print('预订成功,请及时前往支付……')# 发送通知信息self.send_mail(self.receiver_email, '恭喜您,抢到票了,请及时前往12306支付订单!')self.send_sms(self.receiver_mobile, '您的验证码是:8888。请不要把验证码泄露给其他人。')sys.exit(0)else:print('当前车次异常')except Exception as error_info:print(error_info)# 跳转到抢票页面self.driver.visit(self.ticket_url)except Exception as error_info:print(error_info)def send_sms(self, mobile, sms_info):"""发送手机通知短信,用的是-互亿无线-的测试短信"""host = "106.ihuyi.com"sms_send_uri = "/webservice/sms.php?method=Submit"account = "C59782899"pass_word = "19d4d9c0796532c7328e8b82e2812655"params = parse.urlencode({'account': account, 'password': pass_word, 'content': sms_info, 'mobile': mobile, 'format': 'json'})headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}conn = httplib2.HTTPConnectionWithTimeout(host, port=80, timeout=30)conn.request("POST", sms_send_uri, params, headers)response = conn.getresponse()response_str = response.read()conn.close()return response_strdef send_mail(self, receiver_address, content):"""发送邮件通知"""# 连接邮箱服务器信息host = 'smtp.163.com'port = 25sender = 'gxcuizy@163.com'  # 你的发件邮箱号码pwd = 'FatBoy666'  # 不是登陆密码,是客户端授权密码# 发件信息receiver = receiver_addressbody = '<h2>温馨提醒:</h2><p>' + content + '</p>'msg = MIMEText(body, 'html', _charset="utf-8")msg['subject'] = '抢票成功通知!'msg['from'] = sendermsg['to'] = receivers = smtplib.SMTP(host, port)# 开始登陆邮箱,并发送邮件s.login(sender, pwd)s.sendmail(sender, receiver, msg.as_string())if __name__ == '__main__':# 乘客姓名passengers_input = input('请输入乘车人姓名,多人用英文逗号“,”连接,(例如单人“张三”或者多人“张三,李四”,如果学生的话输入“王五()”):')passengers = passengers_input.split(",")while passengers_input == '' or len(passengers) > 4:print('乘车人最少1位,最多4位!')passengers_input = input('请重新输入乘车人姓名,多人用英文逗号“,”连接,(例如单人“张三”或者多人“张三,李四”):')passengers = passengers_input.split(",")# 乘车日期from_time = input('请输入乘车日期(例如“2018-08-08”):')date_pattern = re.compile(r'^\d{4}-\d{2}-\d{2}$')while from_time == '' or re.findall(date_pattern, from_time) == []:from_time = input('乘车日期不能为空或者时间格式不正确,请重新输入:')# 城市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',  # 运城'gzn': '%u5E7F%u5DDE%u5357%2CIZQ',  # 广州南'wzn': '%u68A7%u5DDE%u5357%2CWBZ',  # 梧州南}# 出发站from_input = input('请输入出发站,只需要输入首字母就行(例如北京“bj”):')while from_input not in city_list.keys():from_input = input('出发站不能为空或不支持当前出发站(如有需要,请联系管理员!),请重新输入:')from_station = city_list[from_input]# 终点站to_input = input('请输入终点站,只需要输入首字母就行(例如北京“bj”):')while to_input not in city_list.keys():to_input = input('终点站不能为空或不支持当前终点站(如有需要,请联系管理员!),请重新输入:')to_station = city_list[to_input]# 乘车车次number_input = input('请输入抢票车次号,多车次用英文逗号“,”链接,(例如单车次“Z285”或者多车次“Z285,G110”):')numbers = number_input.split(",")while number_input == '':number_input = input('请重新输入抢票车次号,多车次用英文逗号“,”链接,(例如单车次“Z285”或者多车次“Z285,G110”):')numbers = number_input.split(",")# 座位类型seat_type = input('请输入座位类型(例如“软卧”):')while seat_type == '':seat_type = input('座位类型不能为空,请重新输入:')# 抢票成功,通知该手机号码receiver_mobile = input('请预留一个手机号码,方便抢到票后进行通知(例如:18888888888):')mobile_pattern = re.compile(r'^1{1}\d{10}$')while receiver_mobile == '' or re.findall(mobile_pattern, receiver_mobile) == []:receiver_mobile = input('预留手机号码不能为空或者格式不正确,请重新输入:')receiver_email = input('请预留一个邮箱,方便抢到票后进行通知(例如:test@163.com):')while receiver_email == '':receiver_email = input('预留邮箱不能为空,请重新输入:')# 开始抢票ticket = BrushTicket(passengers, from_time, from_station, to_station, numbers, seat_type, receiver_mobile,receiver_email)ticket.start_brush()

new_qiangpiao_by_no_v2.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-"""
通过splinter刷12306火车票(多个车次查询)
进入登陆页面,可以选择扫码登陆或者账号密码登陆
登陆成功后,接下来的事情,交由脚本来做了,静静的等待抢票结果就好(刷票过程中,浏览器不可关闭)
抢票成功,会进行手机短信和邮件的通知
author: cuizy
time: 2019-01-08
"""import re
from splinter.browser import Browser
from time import sleep
import httplib2
from urllib import parse
import smtplib
from email.mime.text import MIMEText
import timeclass BrushTicket(object):"""买票类及实现方法"""def __init__(self, passengers, from_time, from_station, to_station, numbers, seat_type, receiver_mobile,receiver_email):"""定义实例属性,初始化"""# 乘客姓名self.passengers = passengers# 起始站和终点站self.from_station = from_stationself.to_station = to_station# 车次self.numbers = list(map(lambda number: number.capitalize(),numbers))# 乘车日期self.from_time = from_time# 座位类型所在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.receiver_mobile = receiver_mobileself.receiver_email = receiver_email# 新版12306官网主要页面网址self.login_url = 'https://kyfw.12306.cn/otn/resources/login.html'self.init_my_url = 'https://kyfw.12306.cn/otn/view/index.html'self.ticket_url = 'https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=dc'# 浏览器驱动信息,驱动下载页:https://sites.google.com/a/chromium.org/chromedriver/downloadsself.driver_name = 'chrome'self.driver = Browser(driver_name=self.driver_name)def do_login(self):"""登录功能实现,手动识别验证码进行登录"""self.driver.visit(self.login_url)sleep(1)# 选择登陆方式登陆print('请扫码登陆或者账号登陆……')while True:if self.driver.url != self.init_my_url:sleep(1)else:breakdef start_brush(self):"""买票功能实现"""# 浏览器窗口最大化self.driver.driver.maximize_window()# 登陆self.do_login()# 跳转到抢票页面self.driver.visit(self.ticket_url)sleep(1)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 == self.ticket_url:try:self.driver.find_by_text('查询').click()except Exception as error_info:print(error_info)sleep(1)continuesleep(0.5)count += 1local_date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())print('第%d次点击查询……[%s]' % (count, local_date))try:for car_no in self.numbers:current_tr = self.driver.find_by_xpath('//tr[@datatran="' + car_no + '"]/preceding-sibling::tr[1]')if current_tr:current_time = current_tr.find_by_css('.start-t').textif current_tr.find_by_tag('td')[self.seat_type_index].text == '--':print('%s无此座位类型出售……' % (car_no + '(' + current_time + ')',))sleep(0.2)elif current_tr.find_by_tag('td')[self.seat_type_index].text == '无':print('%s无票……' % (car_no + '(' + current_time + ')',))sleep(0.2)else:# 有票,尝试预订print(car_no + '(' + current_time + ')刷到票了(余票数:' + 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)key_value = 1for p in self.passengers:if '()' in p:p = p[:-1] + '学生' + p[-1:]# 选择用户print('开始选择用户……')self.driver.find_by_text(p).last.click()# 选择座位类型print('开始选择席别……')if self.seat_type_value != 0:self.driver.find_by_xpath("//select[@id='seatType_" + str(key_value) + "']/option[@value='" + str(self.seat_type_value) + "']").first.click()key_value += 1sleep(0.5)if p[-1] == ')':self.driver.find_by_id('dialog_xsertcj_ok').click()sleep(0.1)print('正在提交订单……')self.driver.find_by_id('submitOrder_id').click()sleep(1)# 查看放回结果是否正常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('正在确认订单……')sleep(1)self.driver.find_by_id('qr_submit_id').click()print('预订成功,请及时前往支付……')# 发送通知信息self.send_mail(self.receiver_email, '恭喜您,抢到票了,请及时前往12306支付订单!')self.send_sms(self.receiver_mobile, '您的验证码是:8888。请不要把验证码泄露给其他人。')else:print('当前车次异常')except Exception as error_info:print(error_info)# 跳转到抢票页面self.driver.visit(self.ticket_url)except Exception as error_info:print(error_info)def send_sms(self, mobile, sms_info):"""发送手机通知短信,用的是-互亿无线-的测试短信"""host = "106.ihuyi.com"sms_send_uri = "/webservice/sms.php?method=Submit"account = "C59782899"pass_word = "19d4d9c0796532c7328e8b82e2812655"params = parse.urlencode({'account': account, 'password': pass_word, 'content': sms_info, 'mobile': mobile, 'format': 'json'})headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}conn = httplib2.HTTPConnectionWithTimeout(host, port=80, timeout=30)conn.request("POST", sms_send_uri, params, headers)response = conn.getresponse()response_str = response.read()conn.close()return response_strdef send_mail(self, receiver_address, content):"""发送邮件通知"""# 连接邮箱服务器信息host = 'smtp.163.com'port = 25sender = 'gxcuizy@163.com'  # 你的发件邮箱号码pwd = 'FatBoy666'  # 不是登陆密码,是客户端授权密码# 发件信息receiver = receiver_addressbody = '<h2>温馨提醒:</h2><p>' + content + '</p>'msg = MIMEText(body, 'html', _charset="utf-8")msg['subject'] = '抢票成功通知!'msg['from'] = sendermsg['to'] = receivers = smtplib.SMTP(host, port)# 开始登陆邮箱,并发送邮件s.login(sender, pwd)s.sendmail(sender, receiver, msg.as_string())if __name__ == '__main__':# 乘客姓名passengers_input = input('请输入乘车人姓名,多人用英文逗号“,”连接,(例如单人“张三”或者多人“张三,李四”,如果学生的话输入“王五()”):')passengers = passengers_input.split(",")while passengers_input == '' or len(passengers) > 4:print('乘车人最少1位,最多4位!')passengers_input = input('请重新输入乘车人姓名,多人用英文逗号“,”连接,(例如单人“张三”或者多人“张三,李四”):')passengers = passengers_input.split(",")# 乘车日期from_time = input('请输入乘车日期(例如“2018-08-08”):')date_pattern = re.compile(r'^\d{4}-\d{2}-\d{2}$')while from_time == '' or re.findall(date_pattern, from_time) == []:from_time = input('乘车日期不能为空或者时间格式不正确,请重新输入:')# 城市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',  # 运城'gzn': '%u5E7F%u5DDE%u5357%2CIZQ',  # 广州南'wzn': '%u68A7%u5DDE%u5357%2CWBZ',  # 梧州南}# 出发站from_input = input('请输入出发站,只需要输入首字母就行(例如北京“bj”):')while from_input not in city_list.keys():from_input = input('出发站不能为空或不支持当前出发站(如有需要,请联系管理员!),请重新输入:')from_station = city_list[from_input]# 终点站to_input = input('请输入终点站,只需要输入首字母就行(例如北京“bj”):')while to_input not in city_list.keys():to_input = input('终点站不能为空或不支持当前终点站(如有需要,请联系管理员!),请重新输入:')to_station = city_list[to_input]# 乘车车次number_input = input('请输入抢票车次号,多车次用英文逗号“,”链接,(例如单车次“Z285”或者多车次“Z285,G110”):')numbers = number_input.split(",")while number_input == '':number_input = input('请重新输入抢票车次号,多车次用英文逗号“,”链接,(例如单车次“Z285”或者多车次“Z285,G110”):')numbers = number_input.split(",")# 座位类型seat_type = input('请输入座位类型(例如“软卧”):')while seat_type == '':seat_type = input('座位类型不能为空,请重新输入:')# 抢票成功,通知该手机号码receiver_mobile = input('请预留一个手机号码,方便抢到票后进行通知(例如:18888888888):')mobile_pattern = re.compile(r'^1{1}\d{10}$')while receiver_mobile == '' or re.findall(mobile_pattern, receiver_mobile) == []:receiver_mobile = input('预留手机号码不能为空或者格式不正确,请重新输入:')receiver_email = input('请预留一个邮箱,方便抢到票后进行通知(例如:test@163.com):')while receiver_email == '':receiver_email = input('预留邮箱不能为空,请重新输入:')# 开始抢票ticket = BrushTicket(passengers, from_time, from_station, to_station, numbers, seat_type, receiver_mobile,receiver_email)ticket.start_brush()

new_qiangpiao_by_no_v2_test.py 

#!/usr/bin/env python
# -*- coding: utf-8 -*-"""
通过splinter刷12306火车票(多个车次查询)
进入登陆页面,可以选择扫码登陆或者账号密码登陆
登陆成功后,接下来的事情,交由脚本来做了,静静的等待抢票结果就好(刷票过程中,浏览器不可关闭)
抢票成功,会进行手机短信和邮件的通知
author: cuizy
time: 2019-01-08
"""import re
from splinter.browser import Browser
from time import sleep
import httplib2
from urllib import parse
import smtplib
from email.mime.text import MIMEText
import timeclass BrushTicket(object):"""买票类及实现方法"""def __init__(self, passengers, from_time, from_station, to_station, numbers, seat_type, receiver_mobile,receiver_email):"""定义实例属性,初始化"""# 乘客姓名self.passengers = passengers# 起始站和终点站self.from_station = from_stationself.to_station = to_station# 车次self.numbers = list(map(lambda number: number.capitalize(),numbers))# 乘车日期self.from_time = from_time# 座位类型所在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.receiver_mobile = receiver_mobileself.receiver_email = receiver_email# 新版12306官网主要页面网址self.login_url = 'https://kyfw.12306.cn/otn/resources/login.html'self.init_my_url = 'https://kyfw.12306.cn/otn/view/index.html'self.ticket_url = 'https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=dc'# 浏览器驱动信息,驱动下载页:https://sites.google.com/a/chromium.org/chromedriver/downloadsself.driver_name = 'chrome'self.driver = Browser(driver_name=self.driver_name)def do_login(self):"""登录功能实现,手动识别验证码进行登录"""self.driver.visit(self.login_url)sleep(1)# 选择登陆方式登陆print('请扫码登陆或者账号登陆……')while True:if self.driver.url != self.init_my_url:sleep(1)else:breakdef start_brush(self):"""买票功能实现"""# 浏览器窗口最大化self.driver.driver.maximize_window()# 登陆self.do_login()# 跳转到抢票页面self.driver.visit(self.ticket_url)sleep(1)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 == self.ticket_url:try:self.driver.find_by_text('查询').click()except Exception as error_info:print(error_info)sleep(1)continuesleep(0.5)count += 1local_date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())print('第%d次点击查询……[%s]' % (count, local_date))try:for car_no in self.numbers:current_tr = self.driver.find_by_xpath('//tr[@datatran="' + car_no + '"]/preceding-sibling::tr[1]')if current_tr:current_time = current_tr.find_by_css('.start-t').textif current_tr.find_by_tag('td')[self.seat_type_index].text == '--':print('%s无此座位类型出售……' % (car_no + '(' + current_time + ')',))sleep(0.2)elif current_tr.find_by_tag('td')[self.seat_type_index].text == '无':print('%s无票……' % (car_no + '(' + current_time + ')',))sleep(0.2)else:# 有票,尝试预订print(car_no + '(' + current_time + ')刷到票了(余票数:' + 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)key_value = 1for p in self.passengers:if '()' in p:p = p[:-1] + '学生' + p[-1:]# 选择用户print('开始选择用户……')self.driver.find_by_text(p).last.click()# 选择座位类型print('开始选择席别……')if self.seat_type_value != 0:self.driver.find_by_xpath("//select[@id='seatType_" + str(key_value) + "']/option[@value='" + str(self.seat_type_value) + "']").first.click()key_value += 1sleep(0.5)if p[-1] == ')':self.driver.find_by_id('dialog_xsertcj_ok').click()sleep(0.1)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('正在确认订单……')sleep(1)self.driver.find_by_id('qr_submit_id').click()print('预订成功,请及时前往支付……')# 发送通知信息self.send_mail(self.receiver_email, '恭喜您,抢到票了,请及时前往12306支付订单!')self.send_sms(self.receiver_mobile, '您的验证码是:8888。请不要把验证码泄露给其他人。')else:print('当前车次异常')except Exception as error_info:print(error_info)# 跳转到抢票页面self.driver.visit(self.ticket_url)except Exception as error_info:print(error_info)def send_sms(self, mobile, sms_info):"""发送手机通知短信,用的是-互亿无线-的测试短信"""host = "106.ihuyi.com"sms_send_uri = "/webservice/sms.php?method=Submit"account = "C59782899"pass_word = "19d4d9c0796532c7328e8b82e2812655"params = parse.urlencode({'account': account, 'password': pass_word, 'content': sms_info, 'mobile': mobile, 'format': 'json'})headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}conn = httplib2.HTTPConnectionWithTimeout(host, port=80, timeout=30)conn.request("POST", sms_send_uri, params, headers)response = conn.getresponse()response_str = response.read()conn.close()return response_strdef send_mail(self, receiver_address, content):"""发送邮件通知"""# 连接邮箱服务器信息host = 'smtp.163.com'port = 25sender = 'gxcuizy@163.com'  # 你的发件邮箱号码pwd = 'FatBoy666'  # 不是登陆密码,是客户端授权密码# 发件信息receiver = receiver_addressbody = '<h2>温馨提醒:</h2><p>' + content + '</p>'msg = MIMEText(body, 'html', _charset="utf-8")msg['subject'] = '抢票成功通知!'msg['from'] = sendermsg['to'] = receivers = smtplib.SMTP(host, port)# 开始登陆邮箱,并发送邮件s.login(sender, pwd)s.sendmail(sender, receiver, msg.as_string())if __name__ == '__main__':# 乘客姓名passengers = ('李四',)# 乘车日期from_time = '2019-01-20'date_pattern = re.compile(r'^\d{4}-\d{2}-\d{2}$')# 城市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',  # 运城'gzn': '%u5E7F%u5DDE%u5357%2CIZQ',  # 广州南'wzn': '%u68A7%u5DDE%u5357%2CWBZ',  # 梧州南}# 出发站from_input = 'bj'from_station = city_list[from_input]# 终点站to_input = 'nn'to_station = city_list[to_input]# 乘车车次numbers = ('G529',)# 座位类型seat_type = '二等座'# 抢票成功,通知该手机号码receiver_mobile = '18488888888'receiver_email = 'gxcuizy@163.com'# 开始抢票ticket = BrushTicket(passengers, from_time, from_station, to_station, numbers, seat_type, receiver_mobile,receiver_email)ticket.start_brush()

new_qiangpiao_by_time.py 

#!/usr/bin/env python
# -*- coding: utf-8 -*-"""
通过splinter刷12306火车票(时间段查询)
进入登陆页面,可以选择扫码登陆或者账号密码登陆
登陆成功后,接下来的事情,交由脚本来做了,静静的等待抢票结果就好(刷票过程中,浏览器不可关闭)
抢票成功,会进行手机短信和邮件的通知
author: cuizy
time: 2018-12-28
"""import re
from splinter.browser import Browser
from time import sleep
import sys
import httplib2
from urllib import parse
import smtplib
from email.mime.text import MIMEText
import timeclass BrushTicket(object):"""买票类及实现方法"""def __init__(self, passengers, from_time, from_station, to_station, my_start_time, my_end_time, seat_type, receiver_mobile,receiver_email):"""定义实例属性,初始化"""# 乘客姓名self.passengers = passengers# 起始站和终点站self.from_station = from_stationself.to_station = to_station# 乘车日期self.from_time = from_time# 出发时间段start_arr = my_start_time.split(':')if len(start_arr) == 2:start_time_value = int(start_arr[0]) + int(start_arr[1]) / 60else:start_time_value = int(start_arr[0])self.my_start_time = start_time_valueend_arr = my_end_time.split(':')if len(end_arr) == 2:end_time_value = int(end_arr[0]) + int(end_arr[1]) / 60else:end_time_value = int(end_arr[0])self.my_end_time = end_time_value# 座位类型所在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.receiver_mobile = receiver_mobileself.receiver_email = receiver_email# 新版12306官网主要页面网址self.login_url = 'https://kyfw.12306.cn/otn/resources/login.html'self.init_my_url = 'https://kyfw.12306.cn/otn/view/index.html'self.ticket_url = 'https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=dc'# 浏览器驱动信息,驱动下载页:https://sites.google.com/a/chromium.org/chromedriver/downloadsself.driver_name = 'chrome'self.driver = Browser(driver_name=self.driver_name)def do_login(self):"""登录功能实现,手动识别验证码进行登录"""self.driver.visit(self.login_url)sleep(1)# 选择登陆方式登陆print('请扫码登陆或者账号登陆……')while True:if self.driver.url != self.init_my_url:sleep(1)else:breakdef start_brush(self):"""买票功能实现"""# 浏览器窗口最大化self.driver.driver.maximize_window()# 登陆self.do_login()# 跳转到抢票页面self.driver.visit(self.ticket_url)sleep(1)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 == self.ticket_url:try:self.driver.find_by_text('查询').click()except Exception as error_info:print(error_info)sleep(1)continuesleep(0.5)count += 1local_date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())print('第%d次点击查询……[%s]' % (count, local_date))try:start_list = self.driver.find_by_css('.start-t')for start_time in start_list:current_time = start_time.textcurrent_time_arr = current_time.split(':')if len(current_time_arr) == 2:current_time_value = int(current_time_arr[0]) + int(current_time_arr[1]) / 60else:current_time_value = int(current_time_arr[0])if ((current_time_value >= self.my_start_time) and (current_time_value <= self.my_end_time)):current_tr = start_time.find_by_xpath('ancestor::tr')if current_tr:car_no = current_tr.find_by_css('.number').textif current_tr.find_by_tag('td')[self.seat_type_index].text == '--':print('%s无此座位类型出售,继续……' % (car_no + '(' + current_time + ')',))sleep(0.2)elif current_tr.find_by_tag('td')[self.seat_type_index].text == '无':print('%s无票,继续尝试……' % (car_no + '(' + current_time + ')',))sleep(0.2)else:# 有票,尝试预订print(car_no + '(' + current_time + ')刷到票了(余票数:' + str(current_tr.find_by_tag('td')[self.seat_type_index].text) + '),开始尝试预订……')current_tr.find_by_css('td.no-br>a')[0].click()sleep(0.5)key_value = 1for p in self.passengers:if '()' in p:p = p[:-1] + '学生' + p[-1:]# 选择用户print('开始选择用户……')self.driver.find_by_text(p).last.click()# 选择座位类型print('开始选择席别……')if self.seat_type_value != 0:self.driver.find_by_xpath("//select[@id='seatType_" + str(key_value) + "']/option[@value='" + str(self.seat_type_value) + "']").first.click()key_value += 1sleep(0.2)if p[-1] == ')':self.driver.find_by_id('dialog_xsertcj_ok').click()print('正在提交订单……')self.driver.find_by_id('submitOrder_id').click()sleep(2)# 查看放回结果是否正常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('qr_submit_id').click()print('预订成功,请及时前往支付……')# 发送通知信息self.send_mail(self.receiver_email, '恭喜您,抢到票了,请及时前往12306支付订单!')self.send_sms(self.receiver_mobile, '您的验证码是:8888。请不要把验证码泄露给其他人。')else:print('不存在当前车次【%s】,已结束当前刷票,请重新开启!' % self.number)sys.exit(1)elif current_time_value > self.my_end_time:breakexcept Exception as error_info:print(error_info)# 跳转到抢票页面self.driver.visit(self.ticket_url)except Exception as error_info:print(error_info)def send_sms(self, mobile, sms_info):"""发送手机通知短信,用的是-互亿无线-的测试短信"""host = "106.ihuyi.com"sms_send_uri = "/webservice/sms.php?method=Submit"account = "C59782899"pass_word = "19d4d9c0796532c7328e8b82e2812655"params = parse.urlencode({'account': account, 'password': pass_word, 'content': sms_info, 'mobile': mobile, 'format': 'json'})headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}conn = httplib2.HTTPConnectionWithTimeout(host, port=80, timeout=30)conn.request("POST", sms_send_uri, params, headers)response = conn.getresponse()response_str = response.read()conn.close()return response_strdef send_mail(self, receiver_address, content):"""发送邮件通知"""# 连接邮箱服务器信息host = 'smtp.163.com'port = 25sender = 'gxcuizy@163.com'  # 你的发件邮箱号码pwd = 'FatBoy666'  # 不是登陆密码,是客户端授权密码# 发件信息receiver = receiver_addressbody = '<h2>温馨提醒:</h2><p>' + content + '</p>'msg = MIMEText(body, 'html', _charset="utf-8")msg['subject'] = '抢票成功通知!'msg['from'] = sendermsg['to'] = receivers = smtplib.SMTP(host, port)# 开始登陆邮箱,并发送邮件s.login(sender, pwd)s.sendmail(sender, receiver, msg.as_string())if __name__ == '__main__':# 乘客姓名passengers_input = input('请输入乘车人姓名,多人用英文逗号“,”连接,(例如单人“张三”或者多人“张三,李四”,如果学生的话输入“王五()”):')passengers = passengers_input.split(",")while passengers_input == '' or len(passengers) > 4:print('乘车人最少1位,最多4位!')passengers_input = input('请重新输入乘车人姓名,多人用英文逗号“,”连接,(例如单人“张三”或者多人“张三,李四”):')passengers = passengers_input.split(",")# 乘车日期from_time = input('请输入乘车日期(例如“2018-08-08”):')date_pattern = re.compile(r'^\d{4}-\d{2}-\d{2}$')while from_time == '' or re.findall(date_pattern, from_time) == []:from_time = input('乘车日期不能为空或者时间格式不正确,请重新输入:')# 城市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',  # 运城'gzn': '%u5E7F%u5DDE%u5357%2CIZQ',  # 广州南'wzn': '%u68A7%u5DDE%u5357%2CWBZ',  # 梧州南}# 出发站from_input = input('请输入出发站,只需要输入首字母就行(例如北京“bj”):')while from_input not in city_list.keys():from_input = input('出发站不能为空或不支持当前出发站(如有需要,请联系管理员!),请重新输入:')from_station = city_list[from_input]# 终点站to_input = input('请输入终点站,只需要输入首字母就行(例如北京“bj”):')while to_input not in city_list.keys():to_input = input('终点站不能为空或不支持当前终点站(如有需要,请联系管理员!),请重新输入:')to_station = city_list[to_input]# 出发时间段,最早时间和最晚时间my_start = input('请输入乘车的最早时间(例如“9:00”):')while my_start == '':my_start = input('乘车的最早时间不能为空,请重新输入:')my_end = input('请输入乘车的最晚时间(例如“20:00”):')while my_end == '':my_end = input('乘车的最晚时间不能为空,请重新输入:')# 座位类型seat_type = input('请输入座位类型(例如“软卧”):')while seat_type == '':seat_type = input('座位类型不能为空,请重新输入:')# 抢票成功,通知该手机号码receiver_mobile = input('请预留一个手机号码,方便抢到票后进行通知(例如:18888888888):')mobile_pattern = re.compile(r'^1{1}\d{10}$')while receiver_mobile == '' or re.findall(mobile_pattern, receiver_mobile) == []:receiver_mobile = input('预留手机号码不能为空或者格式不正确,请重新输入:')receiver_email = input('请预留一个邮箱,方便抢到票后进行通知(例如:test@163.com):')while receiver_email == '':receiver_email = input('预留邮箱不能为空,请重新输入:')# 开始抢票ticket = BrushTicket(passengers, from_time, from_station, to_station, my_start, my_end, seat_type, receiver_mobile,receiver_email)ticket.start_brush()

这篇关于利用Python3.6的Splinter模块模拟浏览器刷12306火车票的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/222123

相关文章

python logging模块详解及其日志定时清理方式

《pythonlogging模块详解及其日志定时清理方式》:本文主要介绍pythonlogging模块详解及其日志定时清理方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录python logging模块及日志定时清理1.创建logger对象2.logging.basicCo

Qt spdlog日志模块的使用详解

《Qtspdlog日志模块的使用详解》在Qt应用程序开发中,良好的日志系统至关重要,本文将介绍如何使用spdlog1.5.0创建满足以下要求的日志系统,感兴趣的朋友一起看看吧... 目录版本摘要例子logmanager.cpp文件main.cpp文件版本spdlog版本:1.5.0采用1.5.0版本主要

Python3.6连接MySQL的详细步骤

《Python3.6连接MySQL的详细步骤》在现代Web开发和数据处理中,Python与数据库的交互是必不可少的一部分,MySQL作为最流行的开源关系型数据库管理系统之一,与Python的结合可以实... 目录环境准备安装python 3.6安装mysql安装pymysql库连接到MySQL建立连接执行S

Python使用date模块进行日期处理的终极指南

《Python使用date模块进行日期处理的终极指南》在处理与时间相关的数据时,Python的date模块是开发者最趁手的工具之一,本文将用通俗的语言,结合真实案例,带您掌握date模块的六大核心功能... 目录引言一、date模块的核心功能1.1 日期表示1.2 日期计算1.3 日期比较二、六大常用方法详

使用DrissionPage控制360浏览器的完美解决方案

《使用DrissionPage控制360浏览器的完美解决方案》在网页自动化领域,经常遇到需要保持登录状态、保留Cookie等场景,今天要分享的方案可以完美解决这个问题:使用DrissionPage直接... 目录完整代码引言为什么要使用已有用户数据?核心代码实现1. 导入必要模块2. 关键配置(重点!)3.

python中time模块的常用方法及应用详解

《python中time模块的常用方法及应用详解》在Python开发中,时间处理是绕不开的刚需场景,从性能计时到定时任务,从日志记录到数据同步,时间模块始终是开发者最得力的工具之一,本文将通过真实案例... 目录一、时间基石:time.time()典型场景:程序性能分析进阶技巧:结合上下文管理器实现自动计时

CSS模拟 html 的 title 属性(鼠标悬浮显示提示文字效果)

《CSS模拟html的title属性(鼠标悬浮显示提示文字效果)》:本文主要介绍了如何使用CSS模拟HTML的title属性,通过鼠标悬浮显示提示文字效果,通过设置`.tipBox`和`.tipBox.tipContent`的样式,实现了提示内容的隐藏和显示,详细内容请阅读本文,希望能对你有所帮助... 效

Node.js net模块的使用示例

《Node.jsnet模块的使用示例》本文主要介绍了Node.jsnet模块的使用示例,net模块支持TCP通信,处理TCP连接和数据传输,具有一定的参考价值,感兴趣的可以了解一下... 目录简介引入 net 模块核心概念TCP (传输控制协议)Socket服务器TCP 服务器创建基本服务器服务器配置选项服

JavaWeb-WebSocket浏览器服务器双向通信方式

《JavaWeb-WebSocket浏览器服务器双向通信方式》文章介绍了WebSocket协议的工作原理和应用场景,包括与HTTP的对比,接着,详细介绍了如何在Java中使用WebSocket,包括配... 目录一、概述二、入门2.1 POM依赖2.2 编写配置类2.3 编写WebSocket服务2.4 浏

Python利用自带模块实现屏幕像素高效操作

《Python利用自带模块实现屏幕像素高效操作》这篇文章主要为大家详细介绍了Python如何利用自带模块实现屏幕像素高效操作,文中的示例代码讲解详,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1、获取屏幕放缩比例2、获取屏幕指定坐标处像素颜色3、一个简单的使用案例4、总结1、获取屏幕放缩比例from