采用python自动化模拟浏览器操作

# -*- coding: utf-8 -*-"""
通过splinter刷12306火车票
可以自动填充账号密码并登陆,接下来的事情,交由脚本来做了,静静的等待抢票结果就好(刷票过程中,浏览器不可关闭)
author: Lin
time: 2020-08-18
"""import re
from splinter.browser import Browser
from time import sleep
import sys
import timeclass BrushTicket(object):"""买票类及实现方法"""def __init__(self, user_name, password, passengers, from_time, from_station, to_station, numbers, 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.numbers = list(map(lambda number: number.capitalize(),numbers))# 座位类型所在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/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'# 浏览器驱动信息,驱动下载页:https://sites.google.com/a/chromium.org/chromedriver/downloadsself.driver_name = 'chrome'self.executable_path = r'C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe'self.driver = Browser(driver_name=self.driver_name, executable_path=self.executable_path)def do_login(self):"""登录功能实现,账号进行登录"""self.driver.visit(self.login_url)self.driver.find_by_text('账号登录').click()self.driver.find_by_id("J-userName").fill(self.user_name)self.driver.find_by_id("J-password").fill(self.password)# 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()while self.driver.find_by_text('确定'):self.driver.find_by_text('确定').click()# 跳转到抢票页面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(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(1)if p[-1] == ')':self.driver.find_by_id('dialog_xsertcj_cancel').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('预订成功,请及时前往支付……')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)if __name__ == '__main__':# 此处填入12306账号与密码user_name = u"xxxxxxxxxx"password = u"xxxxxxxxxx"# 乘客姓名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',  # 梧州南'fz': '%u798F%u5DDE%2CFZS',      #福州'pt': '%u8386%u7530%2CPTS',     #莆田}# 出发站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('座位类型不能为空,请重新输入:')# 开始抢票ticket = BrushTicket(user_name, password, passengers, from_time, from_station, to_station, numbers, seat_type)ticket.start_brush()

python自动化模拟浏览器相关推荐

  1. python怎么模拟浏览器交互_干货分享:python爬虫模拟浏览器的两种方法实例分析(赶紧收藏)...

    今天为大家带来的内容是:干货分享:python爬虫模拟浏览器的两种方法实例分析(赶紧收藏) 文章主要介绍了python爬虫模拟浏览器的两种方法,结合实例形式分析了Python爬虫模拟浏览器的两种常见操 ...

  2. python 模拟用户点击浏览器_使用python进行模拟浏览器操作

    使用python完成模拟浏览器操作主要是使用selenium来模拟浏览器,当然还要带上浏览器的驱动比如chromedriver.exe的驱动. 一般使用selenium进行模拟操作需要注意引入一下几个 ...

  3. python爬虫模拟浏览器的两种方法_python爬虫模拟浏览器访问-User-Agent过程解析

    这篇文章主要介绍了python爬虫模拟浏览器访问-User-Agent过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 模拟浏览器访问-Use ...

  4. python实现模拟浏览器登录入口_登录采集——模拟浏览器登录QQ邮箱

    网络爬虫学习中,简单的静态页面数据,难以满足我们的一颗"好学"之心,且现在我们"好奇"的数据往往藏得很深,要么需要登录,要么为动态加载--今天,就来分享一下模拟 ...

  5. python怎么模拟浏览器交互_python+webdriver 模拟用户交互工具

    概述: 使用webdriver(引用摘抄于"Python模拟登陆万能法-微博|知乎" 使用selenium库 步骤: 安装webdriver: Windows: pc:chrome ...

  6. python实现模拟浏览器登录_Python使用win32com实现的模拟浏览器功能示例

    本文实例讲述了Python使用win32com实现的模拟浏览器功能.分享给大家供大家参考,具体如下: # -*- coding:UTF-8 -*- #!/user/bin/env python ''' ...

  7. python中模拟浏览器抓取网页(-)

    对于平时我们抓取网页的内容时,比较倾向于直接利用urllib进行抓取(这里我就基于python的2.7版本进行解说,对于python3之后的版本,是将python中的urllib和urllib2和并成 ...

  8. Python爬虫模拟浏览器的headers、cookie,爬取淘宝网商品信息

    一. 淘宝商品信息定向爬虫 二. 爬虫基础:正则表达式 三. 淘宝页面查看与分析 四. 爬虫源码 一. 淘宝商品信息定向爬虫 注意淘宝的robots.txt不允许任何爬虫爬取,我们只在技术层面探讨这一 ...

  9. python selenium 模拟浏览器

    遇到的问题 (1)按钮无法点击 selenium.common.exceptions.ElementClickInterceptedException: Message: element click ...

最新文章

  1. 一文了解迁移学习经典算法
  2. adb devices 找不到设备的解决方法,亲测,超管用
  3. Android中引入第三方Jar包的方法(java.lang.NoClassDefFoundError)
  4. Java继承多态经典案例分享
  5. SAP CRM 产品主数据搜索时的权限检查实现 - Product search authorization check
  6. 3D 立体 backface-visibility
  7. TemplateSyntaxError at XXXX或页面样式未生效
  8. CUDA:使用nvprof工具计时
  9. Django学习手册 - ORM 外键
  10. 分享几种设为首页的代码
  11. zip 的ZipEntry转换为InputStream
  12. 设计模式之建造者模式与原型模式
  13. 史上最全的WSL安装教程
  14. 移动应用中的AR开发,6款最受欢迎工具推荐
  15. 解决MobaXtem中使用vim不能复制到Windows
  16. win7下安装网络共享打印机 hp LaserJet 1010
  17. 微信小程序开发 | API应用案例(下)
  18. Mecha:将 Mesh 进行到底
  19. 静觅小白爬虫及进阶系列学习笔记
  20. 手把手搭建个人博客(图文教程)

热门文章

  1. python如何开发网站_如何用Python写一个小网站?
  2. 10个值得珍藏的4K高清壁纸网站推荐
  3. HTML5与CSS3学习笔记【第八章 操作样式表】
  4. 数据库 流量切分_ABTEST平行流量切分和分层流量切分高效实现及优缺点分析
  5. win7、win10系统双屏显示任务栏
  6. Mini CFA 考试练习题 Microeconomics
  7. linux调节伽马值软件,四个 Linux 下的“护眼”软件
  8. N-gram模型(基于词表)
  9. 天创速盈带你了解拼多多新店运营技巧
  10. 【数学】 隐函数求导法则