添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
刚毅的硬币  ·  Java、Spring Boot ...·  7 月前    · 
乐观的便当  ·  GROUP BY ...·  1 年前    · 

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

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

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

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

1 # 定位元素的原位置
2 element = driver.find_element_by_id("xx")
3 # 定位元素要移动到的目标位置
4 target = driver.find_element_by_id("xx")
6 ActionChains(driver).drag_and_drop(element, target).perform()

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

------------------------------------------华丽分割------------------------------------------

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

 1 from selenium import webdriver
 2 from selenium.webdriver.common.action_chains import ActionChains
 3 from selenium.common.exceptions import UnexpectedAlertPresentException
 4 from time import sleep
 6 driver = webdriver.Chrome()
 7 driver.get("https://www.helloweba.com/demo/2017/unlock/")
10 dragger = driver.find_elements_by_class_name("slide-to-unlock-handle")[0]
12 action = ActionChains(driver)
14 action.click_and_hold(dragger).perform()  #鼠标左键按下不放
16 for index in range(200):
17     try:
18         action.move_by_offset(2, 0).perform() #平行移动鼠标
19     except UnexpectedAlertPresentException:
20         break
21     action.reset_actions()
22     sleep(0.1)  #等待停顿时间
25 # 打印警告框提示
26 success_text = driver.switch_to.alert.text
27 print(success_text)
29 sleep(5)
31 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!