如何使用 Selenium ChromeDriver 执行右键单击操作?

seleniumautomation testingtesting tools

我们可以使用 Selenium ChromeDriver 执行右键单击操作。右键单击网页元素后,会显示上下文菜单。例如,如果我们右键单击文本区域,就会出现一个包含多个选项的附加菜单。

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://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // 识别元素
      WebElement l=driver.findElement(By.xpath("//*[text()='Library']"));
      // Actions 类,包含 moveToElement() 和 contextClick() 函数
      Actions a = new Actions(driver);
      a.moveToElement(l).contextClick().build().perform();
      driver.quit();
   }
}

输出


相关文章