如何在 Selenium 中使用 Python 對元素執行滑鼠釋放操作?


我們可以藉助 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 物件後,我們可以像一個排隊的鏈一樣,依次執行許多操作。

release() – 此方法對元素執行釋放滑鼠按鈕的操作。

語法

release(args)

其中 args 是從該元素釋放滑鼠的位置。如果省略引數,則將釋放滑鼠的當前位置。

#element
source = driver.find_element_by_id("name")
#action chain object
action = ActionChains(driver)
# move to element operation
action.click(source)
# release the mouse up
action.release(source)
# perform the action
action.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)
# click the element
action.click(source)
# release the element
action.release(source)
# perform the action
action.perform()
#to close the browser
driver.close()

更新於: 2020-07-29

845 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告