Python + Selenium 小技巧之滑动解锁操作的处理

Python + Selenium 小技巧之滑动解锁操作的处理

滑动解锁是当下比较流行的解锁方式。

当我们单击滑块地,实际改变的只是CSS样式,HTML代码段如下。

<div class="slide-to-unlock-progress" style="background-color: rgb(255, 233, 127); height: 36px;"></div>
<div class="slide-to-unlock-handle" style="background-color: rgb(255, 255, 255); height: 38px; line-height: 38px; width: 37px;"></div>

https://www.helloweba.com/demo/2017/unlock/

  • slide-to-unlock-handle表示滑块。在滑动过程中,滑块 的左边距会逐渐变大,因为它在向右移动。
  • slide-to-unlock-progress表示滑过之后的背景色,背景色的区域会逐渐增加,同样因为滑块在向右移动。
import time
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.common.exceptions import UnexpectedAlertPresentException

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

# 定位滑块
slider = browser.find_elements_by_class_name("slide-to-unlock-handle")[0]
action = ActionChains(browser)
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 = browser.switch_to.alert.text
print(success_text)

在这个脚本中,用到下面几个方法。

  • click_and_hold() 单击并按下鼠标左键。
  • move_by_offset() 移动鼠标,第一个参数为x坐标距离,第二个参数为y坐标距离。
  • reset_actions() 重置action。

执行完成,滑动效果如下所示:

接下来,我们来看另一种应用形式,上下滑动选择日期:

在上一个例子中,我们采用了ActionChains类可以实现滑动操作,这里我们换一种思路,通过TouchActions类实现上下滑动,进行日期的选择。

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

browser = webdriver.Chrome()
browser.get("https://www.jq22.com/yanshi4976")

time.sleep(2)
browser.switch_to.frame("iframe")
browser.find_element_by_id("appData").click()

# 定位要滑动的年、月、日
dwwos = browser.find_elements_by_class_name("dwwo")
year = dwwos[0]
month = dwwos[1]
day = dwwos[2]

action = webdriver.TouchActions(browser)
action.scroll_from_element(year, 0, 5).perform()
action.scroll_from_element(month, 0, 30).perform()
action.scroll_from_element(day, 0 , 30).perform()

这里使用TouchActions类中的scroll_from_element()方法滑动元素,参数如下:

  • on_element 滑动的元素。
  • xoffset x坐标距离。
  • yoffset y坐标距离。

文章作者: &娴敲棋子&
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 &娴敲棋子& !
评论
  目录