如何使用 Selenium 建立右鍵單擊功能?
在網頁上的任何元素上執行右鍵單擊以顯示其上下文選單。例如,如果我們在編輯框上右鍵單擊,就會顯示一個包含多個選項的新選單。
Selenium 使用 Actions 類執行右鍵單擊操作。contextClick() 是 Actions 類中的一個方法,用於執行右鍵單擊;在選單開啟後,我們可以透過自動化從選單中選擇一個選項。
首先,我們需要使用 moveToElement() 方法將滑鼠移動到元素中間,然後執行右鍵單擊。接下來,使用 build() 方法執行復合操作。最後,perform() 方法實際執行這些操作。
我們需要在程式碼中匯入 org.openqa.selenium.interactions.Actions才能使用 Actions 類及其方法。
示例
程式碼實現。
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.interactions.Action; import org.openqa.selenium.interactions.Actions; public class RightClick{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = "https://tutorialspoint.tw/index.htm"; driver.get(url); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); // identify element WebElement l=driver.findElement(By.id("gsc-i-id1")); // Actions class with moveToElement() and contextClick() Actions a = new Actions(driver); a.moveToElement(l).contextClick().build().perform(); driver.quit(); } }
輸出
廣告