【Selenium】UI自动化实践——滑动滑块验证码登录

实战题目

使用python+selenium实现12306网站的登录及买票的UI自动化。

解题方案

UI自动化步骤:

  1. 打开浏览器
  2. 访问网站
  3. 找到元素(Selenium提供了8种定位方式,推荐id, xpath, css)、操作元素
  4. 滑块验证码破解:找到滑块 >> 按住鼠标 >> 拖动到最右边 >> 放开鼠标

代码:

import time

from selenium import webdriver
from selenium.webdriver import ActionChains, Keys
from selenium.webdriver.chrome.options import Options

# 驱动自动控制软件标识(js就检测不出来这个浏览器是手动打开的还是自动化打开的)
options = Options()
options.add_experimental_option('excludeSwitches', ['enable-automation'])
options.add_argument('--disable-blink-features=AutomationControlled')

# 打开浏览器
wd = webdriver.Chrome(options=options)
# 最大化
wd.maximize_window()
# 隐式等待
wd.implicitly_wait(5)

# 打开网站
wd.get('https://kyfw.12306.cn/otn/resources/login.html')

# 定位元素
wd.find_element('xpath', '//*[@id="J-userName"]').send_keys('username')
wd.find_element('xpath', '//*[@id="J-password"]').send_keys('pwd')
wd.find_element('xpath', '//*[@id="J-login"]').click()


# 验证码破解
silder = wd.find_element('xpath', '//*[@id="nc_1_n1z"]')

# 快捷导入【Alt+Enter】
action = ActionChains(wd)
# 按住滑块
action.click_and_hold(silder)
# 滑到最右边
action.move_by_offset(350, 0)
# 松开鼠标
action.release()
# 让action生效
action.perform()

time.sleep(3)

# 买票
wd.get('https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=dc')
# 输入出发地
wd.find_element('xpath', '//*[@id="fromStationText"]').click()
wd.find_element('xpath', '//*[@id="fromStationText"]').send_keys('深圳北 ')
wd.find_element('xpath', '//*[@id="fromStationText"]').send_keys(Keys.BACKSPACE)
wd.find_element('xpath', '//*[@id="citem_0"]').click()
# 输入目的地
wd.find_element('xpath', '//*[@id="toStationText"]').click()
wd.find_element('xpath', '//*[@id="toStationText"]').send_keys('广州南 ')
wd.find_element('xpath', '//*[@id="toStationText"]').send_keys(Keys.BACKSPACE)
wd.find_element('xpath', '//*[@id="citem_0"]').click()
# 查询
wd.find_element('xpath', '//*[@id="query_ticket"]').click()

time.sleep(6)

在这里插入图片描述

注意事项

  1. 定位不到滑块:no such element: Unable to locate element: {“method”:“xpath”,“selector”:“//*[@id=“nc_1_n1z”]”}
    解决方案: 代码运行太快,验证码弹窗还未显示,添加隐式等待即可。
  2. 拖动滑块后滑块报错如下:
    在这里插入图片描述
    代码滑动太快,网页识别成非人工行为所以报错。
    解决方案: 添加如下浏览器options
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_experimental_option('excludeSwitches', ['enable-automation'])
options.add_argument('--disable-blink-features=AutomationControlled')

wd = webdriver.Chrome(options=options)
  1. 对于输入选择框,发现直接使用send_keys()没用。
    解决方案:
    先点击输入框 >> 在输入后面加一个空格 >> 再模拟按键操作删除这个空格(触发了键盘事件)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值