Python中Selenium模拟JQuery滑动解锁实例

yipeiwu_com6年前Python基础

本文介绍了Python中Selenium模拟JQuery滑动解锁实例,分享给大家,也给自己留个笔记

滑动解锁一直做UI自动化的难点之一,我补一篇滑动解锁的例子,希望能给初做Web UI自动化测试的同学一些思路。

首先先看个例子。

当我手动点击滑块时,改变的只是样式:

1、slide-to-unlock-handle 表示滑块,滑块的左边距在变大(因为它在向右移动嘛!)

2、Slide-tounlock-progress 表示滑过之后的背景黄色,黄色的宽度在增加,因为滑动经过的地方都变黄了。

除些之外,没其它任何变化了,所以我们利用鼠标的拖动貌似不行!因为鼠标的拖动是将一个元素移动到另一个元素上。这样:

# 定位元素的原位置
element = driver.find_element_by_id("xx")
# 定位元素要移动到的目标位置
target = driver.find_element_by_id("xx")

ActionChains(driver).drag_and_drop(element, target).perform()

但在我手动演示的过程中,元素的位置并没有发生变化。

接下来看我是怎么实现的。

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import UnexpectedAlertPresentException
from time import sleep

driver = webdriver.Chrome()
driver.get("https://www.helloweba.com/demo/2017/unlock/")


dragger = driver.find_elements_by_class_name("slide-to-unlock-handle")[0]

action = ActionChains(driver)

action.click_and_hold(dragger).perform() #鼠标左键按下不放

for index in range(200):
  try:
    action.move_by_offset(2, 0).perform() #平行移动鼠标
  except UnexpectedAlertPresentException:
    break
  action.reset_actions()
  sleep(0.1) #等待停顿时间


# 打印警告框提示
success_text = driver.switch_to.alert.text
print(success_text)

sleep(5)

driver.quit()

driver.find_elements_by_class_name("slide-to-unlock-handle")[0]

首先,我要操作的页面上有好几个滑块,我先通过通过class属性找到所有的里面的第一个。

click_and_hold()

通过click_and_hold()方法对滑块按下鼠标左键。

move_by_offset()

接下来就是通过for循环动滑块的位置,move_by_offset()方法第一个参数是X轴,第二个参数是Y轴,单位为像素。因为是平行移动,所以Y设置为0。 X每次移动两2个像素。

当解锁成功后会抛UnexpectedAlertPresentException异常,捕捉后跳出循环。

每次循环休眠0.1秒,时间间隔越小,移动越顺滑哟!

核心的几步介绍完了,接下来就是获取警告框上面的提示信息并打印,然后关闭浏览器。

打印结果为:

successfully unlock!

 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。 

相关文章

在python中,使用scatter绘制散点图的实例

如下所示: # coding=utf-8 import matplotlib.pyplot as plt x_values=[1,2,3,4,5] y_values=[1,4,9,...

python3 实现调用串口功能

python调用串口,写入数据 #!/usr/bin/python3 import serial def serialTest(): try: port = "C...

python实现任意位置文件分割的实例

应用场景 在嵌入式开发中,常常需要将一个binary文件分割成多个文件,或者将一个binary的某块区域抓成一个单独文件。本篇blog以python为例,实现了以上需求; 实现代码...

Python 可爱的大小写

函数较简单,看下面的例子: 复制代码 代码如下:s = 'hEllo pYthon' print s.upper() print s.lower() print s.capitalize...

Python中easy_install 和 pip 的安装及使用

easy_install 和 pip的介绍: easy_install和pip都是用来下载安装Python一个公共资源库PyPI 的相关资源包的,pip是easy_install的...