如何使用 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 物件後,我們可以像一個排隊的鏈一樣,一個接一個地執行許多操作。

context_click() - 此方法對頁面上的元素執行右鍵點選操作。

語法

context_click(args)

其中 args 是要右鍵點選的元素。如果省略,則執行當前滑鼠位置的點選操作。

#element
source = driver.find_element_by_id("name")
#action chain object
action = ActionChains(driver)
# right click operation
action.context_click(source)

示例

右鍵點選操作的程式碼實現。

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)
# right click operation and then perform
action.context_click(source).perform()
#to close the browser
driver.close()

更新於: 2020-07-29

5K+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告