如何在使用 python 的 Selenium 中對元素執行滑鼠移動操作?
透過 Action Chains 類,我們可以在 Selenium 中對元素執行滑鼠移動。此類通常用於自動化互動,例如上下文選單點選、滑鼠按鈕操作、按鍵和滑鼠移動。
這些型別的操作主要常見於複雜場景中,例如拖放和懸停在頁面上的元素上。Action Chains 類的方**法由高階指令碼利用。我們可以藉助 Selenium 中的**Action Chains 來操縱 DOM。
動作鏈物件以佇列的形式實現**ActionChains,然後執行 perform() 方法。在呼叫 perform() 方法時,將執行動作鏈上的所有動作。
建立**Action Chain**物件的方法如下 -
首先,我們需要匯入**Action Chain 類,然後將驅動程式作為引數傳遞給它。
現在所有動作鏈的操作都可以藉助此物件完成。
語法
建立**Action Chains 物件的語法 -
from selenium import webdriver
# import Action chains from selenium.webdriver import ActionChains # create webdriver object driver = webdriver.Firefox() # create action chain object action = ActionChains(driver)
建立**Action Chains 物件後,我們可以逐個執行眾多操作,就像一個已排隊的鏈條。
move_to_element() - 此方法執行將滑鼠移動到頁面上元素中央的操作。
語法
move_to_element(args)
其中,args 是要移動到的元素。
#element source = driver.find_element_by_id("name") #action chain object action = ActionChains(driver) # move to element operation action.move_to_element(source).click().perform()
示例
移動到某個元素的程式碼實現。
from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.common.keys import Keys #browser exposes an executable file #Through Selenium test we will invoke the executable file which will then #invoke actual browser driver = webdriver.Chrome(executable_path="C:\chromedriver.exe") # to maximize the browser window driver.maximize_window() #get method to launch the URL driver.get("https://tutorialspoint.tw/about/about_careers.htm") #to refresh the browser driver.refresh() # identifying the source element source= driver.find_element_by_xpath("//*[text()='Company']"); # action chain object creation action = ActionChains(driver) # move to the element and click then perform the operation action.move_to_element(source).click().perform() #to close the browser driver.close()
廣告