Selenium模擬JQuery滑動解鎖

滑動解鎖一直作UI自動化的難點之一,我補一篇滑動解鎖的例子,但願能給初作Web UI自動化測試的同窗一些思路。web

 

首先先看個例子。瀏覽器

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

 

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

一、slide-to-unlock-handle 表示滑塊,滑塊的左邊距在變大(由於它在向右移動嘛!)ui

二、Slide-tounlock-progress 表示滑過以後的背景黃色,黃色的寬度在增長,由於滑動通過的地方都變黃了。spa

 

除些以外,沒其它任何變化了,因此咱們利用鼠標的拖動貌似不行!由於鼠標的拖動是將一個元素移動到另外一個元素上。這樣:3d

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

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

但在我手動演示的過程當中,元素的位置並無發生變化。code

 

---------------華麗分割-------------------------------------orm

接下來看我是怎麼實現的。blog

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!

 

相關文章
相關標籤/搜索