1. 實現目標
打開https://www.helloweba.net/demo/2017/unlock/,自動測試鼠標放置在滑塊上,實現自動滑動。
2. 實現代碼
其中,獲得某個具體額滑動塊,可找到所有class_name爲slide-to-unlock-handle的,選擇第0-第3項;
click_and_hold():單擊並按下鼠標左鍵;
move_by_offset():移動鼠標,第一個參數爲x座標距離,第二個參數爲y座標距離;
reset_action():重置action。
from time import sleep
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.common.exceptions import UnexpectedAlertPresentException
driver = webdriver.Chrome()
driver.get("http://www.helloweba.com/demo/2017/unlock/")
# 定位滑動塊
slider = driver.find_elements_by_class_name("slide-to-unlock-handle")[1]
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)
3. 實現結果
在該頁面中,可以看到滑塊在以0.1s停頓的時間間隔進行緩緩向右滑動。當滑動到最後端,彈出解鎖成功的彈窗。