如何使用 Selenium ChromeDriver 執行右鍵單擊?
我們可以使用 Selenium ChromeDriver 來執行右鍵單擊。在 Web 元素上右鍵單擊時,上下文選單將顯示。例如,如果我們在文字區域上單擊滑鼠右鍵,就會彈出一個包含幾個選項的附加選單。
Selenium 中的 Actions 類負責模擬此滑鼠操作。Actions 類的提供的contextClick() 方法來執行此操作,從上下文選單中選擇任何選項。
要執行此整個操作,我們首先要使用**moveToElement() 方法將滑鼠移動到元素的中間,然後應用 contextClick() 方法。此外,我們必須執行 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 RightClickOperation{ 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.xpath("//*[text()='Library']")); // Actions class with moveToElement() and contextClick() Actions a = new Actions(driver); a.moveToElement(l).contextClick().build().perform(); driver.quit(); } }
輸出
廣告