Selenium模擬JQuery滑動解鎖


滑動解鎖一直做UI自動化的難點之一,我補一篇滑動解鎖的例子,希望能給初做Web UI自動化測試的同學一些思路。

 

首先先看個例子。

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

 

當我手動點擊滑塊時,改變的只是樣式:

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!

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM