右键单击并 Double 点击进入 Selenium
⚡ 智能摘要
右键单击并 Double 点击进入 Selenium 鼠标操作是通过 Actions 类实现的自动化操作。本教程演示了这两种操作的实际应用。 Java 代码、真实测试场景以及驱动它们的方法 Selenium WebDriver。

右键单击 Selenium
右键单击操作 Selenium WebDriver 使用 Actions 类来实现操作。该操作也称为上下文点击。预定义 contextClick() Actions 类的该方法执行右键单击操作。以下是基本语法。
Actions actions = new Actions(driver);
WebElement elementLocator = driver.findElement(By.id("ID"));
actions.contextClick(elementLocator).perform();
如何右键单击 Selenium
以下场景启动 Guru99 演示页面,执行右键单击,并从出现的上下文菜单中选择一个选项。
测试场景:
- 发射: https://demo.guru99.com/test/simple_context_menu.html
- 点击“右键点击我”按钮
- 点击显示菜单中的“编辑”链接
- 点击提示框中的“确定”按钮。
- 关闭浏览器
代码:
package test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class ContextClick {
public static void main(String[] args) throws InterruptedException {
WebDriver driver;
System.setProperty("webdriver.chrome.driver", "X://chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://demo.guru99.com/test/simple_context_menu.html");
driver.manage().window().maximize();
Actions action = new Actions(driver);
WebElement link = driver.findElement(By.cssSelector(".context-menu-one"));
action.contextClick(link).perform();
WebElement element = driver.findElement(By.cssSelector(".context-menu-icon-copy"));
element.click();
}
}
结果: 此时会显示上下文菜单,并选择“编辑”选项。
Double 点击进入 Selenium
遵循同样的基于行动的模式, Double 点击进入 Selenium WebDriver 使用预定义的 doubleClick() 方法。Actions 类是用于复合鼠标和键盘操作(例如右键单击、拖放和悬停)的标准辅助类。
Actions actions = new Actions(driver);
WebElement elementLocator = driver.findElement(By.id("ID"));
actions.doubleClick(elementLocator).perform();
执行流程如下:
- 使用驱动程序实例实例化 Actions 对象。
- 使用以下方式定位目标元素
findElement. - 电话联系
doubleClick()和链perform()执行。
如何 Double 点击进入 Selenium
下一个场景演示了如何通过完整的双击操作触发一个事件。 Java脚本发出警报并通过程序进行确认。
测试场景:
- 发射: https://demo.guru99.com/test/simple_context_menu.html
- Double 点击按钮“Double“点击查看提醒”
- 点击提示框中的“确定”按钮。
代码:
package test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.Alert;
public class DoubleClickDemo {
public static void main(String[] args) throws InterruptedException {
WebDriver driver;
System.setProperty("webdriver.chrome.driver", "X://chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://demo.guru99.com/test/simple_context_menu.html");
driver.manage().window().maximize();
Actions action = new Actions(driver);
WebElement link = driver.findElement(By.xpath("//button[text()='Double-Click Me To See Alert']"));
action.doubleClick(link).perform();
Alert alert = driver.switchTo().alert();
System.out.println("Alert Text\n" + alert.getText());
alert.accept();
}
}
结果: 弹出提示框,提示文本打印出来。 Eclipse 安慰。



