如何在 Selenium 中使用 Actions 对元素执行右键单击操作?

software testingautomation testingselenium web driver

我们可以借助 Selenium 的 Actions 对元素执行右键单击操作。要执行右键单击操作,我们将使用 `contextClick()` 方法。首先,我们需要使用 `moveToElement()` 方法移动到目标元素,然后使用 `contextClick()` 方法执行右键单击操作。最后,使用 `build().perform()` 执行所有步骤。

示例

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import java.util.concurrent.TimeUnit;
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://www.tutorialspoint.com/questions/index.php";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      // contextClick() method for right click to an element after moving the //mouse to with the          moveToElement()
      Actions a = new Actions(driver);
      a.moveToElement(driver.findElement(By.xpath(“input[@type=’text’]))).
      contextClick().
      build().perform();
      driver.quit();
   }
}

相关文章