🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## **4.18 滑动解锁** 滑动解锁是目前比较流行的解锁方式,如图 4-11 所示。 ![](https://img.kancloud.cn/90/d4/90d450836681a2b76dcc2f0118192cb3_448x289.png) 当我们单击滑块时,改变的只是 CSS 样式,HTML 代码段如下。 ``` <div class="slide-to-unlock-progress" style="background-color: rgb(255, 233, 127); height: 36px; width: 0px;"> </div> <div class="slide-to-unlock-handle" style="background-color: rgb(255, 255, 255); height: 38px; line-height: 38px; width: 37px; left: 0px;"> </div> ``` slide-to-unlock-handle 表示滑块。在滑动过程中,滑块的左边距会逐渐变大,因为它在向右移动。 slide-to-unlock-progress 表示滑过之后的背景色,背景色的区域会逐渐增加,因为滑块在向右移动。 ``` from time import sleep from selenium import webdriver from selenium.webdriver import ActionChains from selenium.common.exceptions import UnexpectedAlertPresentException driver = webdriver.Chrome() driver.get("https://www.helloweba.com/demo/2017/unlock/") # 定位滑动块 slider = driver.find_elements_by_class_name("slide-to-unlock-handle")[0] action = ActionChains(driver) action.click_and_hold(slider).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) ``` 在这个脚本中,用到下面几个方法。 * click_and_hold(): 单击并按下鼠标左键,在鼠标事件中介绍过。 * move_by_offset():移动鼠标,第一个参数为 x 坐标距离,第二个参数为 y 坐标距离。 * reset_action():重置 action。 执行完成,滑动效果如图 4-12 所示。 ![](https://img.kancloud.cn/00/fc/00fc7e200001e25141405fd195c56b41_417x265.png) 接下来,再看另外一种应用,上下滑动选择日期,如图 4-13 所示。 ![](https://img.kancloud.cn/d2/d7/d2d78160c86e06a6e2677e3a49115db1_629x638.png) 参考前面的操作,通过 ActionChains 类可以实现上下滑动选择日期,但是这里要介绍另外一种方法,即通过 TouchActions 类实现上下滑动选择日期。 ``` from selenium import webdriver from selenium.webdriver import ActionChains driver = webdriver.Chrome() driver.get("https://www.baidu.com") # 定位到要悬停的元素 above = driver.find_element_by_link_text("新闻") # 对定位到的元素执行鼠标悬停操作 ActionChains(driver).move_to_element(above).perform() ``` 这里使用 TouchActions 类中的 scroll_from_element()方法滑动元素,参数如下。 * on_element:滑动的元素。 * xoffset:x 坐标距离。 * yoffset:y 坐标距离。