Selenium 中的 Actions 類是什麼?


Selenium 可以藉助 ActionsChains 類執行滑鼠移動、按鍵、懸停在元素上、拖放操作等操作。我們必須建立 ActionChains 類的例項,該例項將所有操作儲存在佇列中。

然後呼叫 perform 方法,該方法實際上按佇列中排序的順序執行任務。我們必須新增語句 from selenium.webdriver import ActionChains 來使用 ActionChains 類。

語法

#Method 1 - chained pattern

e =driver.find_element_by_css_selector(".txt")

a = ActionChains(driver)

a.move_to_element(e).click().perform()

#Method 2 - queued actions one after another

e =driver.find_element_by_css_selector(".txt")

a = ActionChains(driver)

a.move_to_element(e)

a.click()

a.perform()

在以上兩種方法中,操作都是按呼叫的順序依次執行的,一個接一個。

ActionChains 類的 方法如下所示:

  • click - 用於點選網頁元素。

  • click_and_hold - 用於在網頁元素上按住滑鼠左鍵。

  • double_click - 用於雙擊網頁元素。

  • context_click - 用於右鍵點選網頁元素。

  • drag_and_drop_by_offset - 用於首先在源元素上按下滑鼠左鍵,導航到目標偏移量,最後釋放滑鼠。

  • drag_and_drop - 用於首先在源元素上按下滑鼠左鍵,導航到目標元素,最後釋放滑鼠。

  • key_up - 用於釋放修飾鍵。

  • key_down - 用於按鍵,但不釋放。

  • move_to_element - 用於將滑鼠移動到網頁元素的中間。

  • move_by_offset - 用於將滑鼠移動到當前滑鼠位置的偏移量。

  • perform - 用於執行排隊的操作。

  • move_to_element_by_offset - 用於將滑鼠移動到特定網頁元素的偏移量。偏移量是從網頁元素的左上角測量的。

  • release - 用於在網頁元素上釋放按住的滑鼠按鈕。

  • pause - 用於停止所有輸入,持續時間以秒為單位。

  • send_keys - 用於向當前活動元素髮送按鍵。

  • reset_actions - 用於刪除本地和遠端儲存的所有操作。

讓我們使用 ActionChains 方法點選連結 - 隱私政策。

示例

from selenium import webdriver
from selenium.webdriver import ActionChains
driver = webdriver.Chrome(executable_path='../drivers/chromedriver')

#implicit wait time
driver.implicitly_wait(5)

#url launch
driver.get("https://tutorialspoint.tw/about/about_careers.htm")

#identify element
s = driver.find_element_by_link_text("Privacy Policy")

#instance of ActionChains
a= ActionChains(driver)

#move to element
a.move_to_element(s)

#click
a.click().perform()

#get page title
print('Page title: ' + driver.title)

#driver quit
driver.close()

輸出

更新於: 2022年2月8日

608 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告