在Selenium Webdriver中,如何从右键菜单中选择一个选项 - Java

32

我正在使用Selenium webdriver。我无法选择右键打开的选项中的选项(比如第二个)。

在我的当前代码中,我能够右键单击webElement,但无法从右键单击后打开的列表中选择选项,因为它会自动消失。

Actions action= new Actions(driver);
action.contextClick(productLink).build().perform();

使用此代码后,我可以右键单击,但右键菜单会自动消失。我想选择右键菜单中的第二个选项。

请帮忙!!!

12个回答

38

要从上下文菜单中选择项目,您只需使用键按下事件移动鼠标位置,如下所示:

Actions action= new Actions(driver);
action.contextClick(productLink).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.RETURN).build().perform();

希望这对你有用。祝你拥有美好的一天 :)


对我没用,我尝试了以下代码: Actions builder = new Actions(driver); builder.contextClick(element) .sendKeys(Keys.ARROW_DOWN) .sendKeys(Keys.ARROW_DOWN) .sendKeys(Keys.RETURN) .build().perform(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.close(); - Kumrun Nahar Keya
对我来说也不起作用 - undefined

10

*您可以使用Robot类来实现此功能,尝试以下代码:

Actions action = new Actions(driver);
action.contextClick(WebElement).build().perform();
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);

[更新]

注意:在执行机器人操作时,您的浏览器应始终处于焦点状态,即在前台运行,否则前台的任何其他应用程序都将接收该操作。


9

这是更好的方法,而且它是成功的:

Actions oAction = new Actions(driver);
oAction.moveToElement(Webelement);
oAction.contextClick(Webelement).build().perform();  /* this will perform right click */
WebElement elementOpen = driver.findElement(By.linkText("Open")); /*This will select menu after right click */

elementOpen.click();

6
也许适用于自定义菜单,但不适用于Chrome浏览器菜单。 - iirekm

5
我们将使用WebDriver动作类并执行右键单击。以下是语法: ``` 我们将借助 WebDriver action 类来执行右键单击。以下是语法: ```
Actions action = new Actions(driver).contextClick(element);
action.build().perform();

以下是我们在示例中遵循的步骤:
  1. 识别元素
  2. 等待元素出现
  3. 现在执行上下文点击操作
  4. 然后需要选择所需的链接。

包com.pack.rightclick;

    import org.openqa.selenium.Alert;
    import org.openqa.selenium.By;
    import org.openqa.selenium.NoSuchElementException;
    import org.openqa.selenium.StaleElementReferenceException;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.interactions.Actions;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.WebDriverWait;
    import org.testng.Assert;
    import org.testng.annotations.AfterClass;
    import org.testng.annotations.BeforeClass;
    import org.testng.annotations.Test;

public class RightClickExample {

    WebDriver driver;

    String URL = "http://medialize.github.io/jQuery-contextMenu/demo.html";

    @BeforeClass
    public void Setup() {
        driver = new FirefoxDriver();
        driver.manage().window().maximize();
    }

    @Test
    public void rightClickTest() {
        driver.navigate().to(URL);
        By locator = By.cssSelector(".context-menu-one.box");
        WebDriverWait wait = new WebDriverWait(driver, 5);
        wait.until(ExpectedConditions.presenceOfElementLocated(locator)); 
        WebElement element=driver.findElement(locator);
        rightClick(element);
        WebElement elementEdit =driver.findElement(By.cssSelector(".context-menu-item.icon.icon-edit>span"));
        elementEdit.click();
        Alert alert=driver.switchTo().alert();
        String textEdit = alert.getText();
        Assert.assertEquals(textEdit, "clicked: edit", "Failed to click on Edit link");
    }

    public void rightClick(WebElement element) {
        try {
            Actions action = new Actions(driver).contextClick(element);
            action.build().perform();

            System.out.println("Sucessfully Right clicked on the element");
        } catch (StaleElementReferenceException e) {
            System.out.println("Element is not attached to the page document "
                    + e.getStackTrace());
        } catch (NoSuchElementException e) {
            System.out.println("Element " + element + " was not found in DOM "
                    + e.getStackTrace());
        } catch (Exception e) {
            System.out.println("Element " + element + " was not clickable "
                    + e.getStackTrace());
        }
    }

    @AfterClass
    public void tearDown() {
        driver.quit();
    }


}

“Save link as…” 的 CSS 定位器是什么? - Tony

2

不要试图在鼠标上右键单击,而是使用键盘快捷方式:

双击元素 -> 按住Shift并按F10。

最初的回答:

使用Shift + F10代替鼠标右键单击。

Actions action = new Actions(driver);

//Hold left shift and press F10
action.MoveToElement(element).DoubleClick().KeyDown(Keys.LeftShift).SendKeys(Keys.F10).KeyUp(Keys.LeftShift).Build().Perform();

双击元素 -> 按住Shift键并按F10键。帮了我大忙!! - mathematics-and-caffeine

1
更好更简单的方法。
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.cssSelector("a[href^='https://www.amazon.in/ap/signin']"))).contextClick().build().perform();

你可以在 cssSelector 的位置使用任何选择器。


1

如果不支持Action类,也可以使用JavaScript执行器实现右键单击:

JavascriptExecutor js = (JavascriptExecutor) driver;

String javaScript = "var evt = document.createEvent('MouseEvents');"
                + "var RIGHT_CLICK_BUTTON_CODE = 2;"
                + "evt.initMouseEvent('contextmenu', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, RIGHT_CLICK_BUTTON_CODE, null);"
                + "arguments[0].dispatchEvent(evt)";

js.executeScript(javaScript, element);

1

在执行上下文点击(context click())后,您可能需要将鼠标移动到任何特定位置,就像这样 -

Actions action = new Actions(driver);
actions.contextClick(link).moveByOffset(x,y).click().build().perform();

要了解moveByOffset(x,y)的工作原理,请查看此处;

我希望这个方法能够奏效。您需要计算xy的偏移值;

最好的方法是在右键单击后找到每个选项按钮的大小,然后如果您点击第二个选项。

x = 选项按钮宽度/2

y = 2*(每个选项按钮的大小)


@ Hari Reddy - 感谢您的回答。在当前的解决方案中,问题是我无法获得偏移值,因为 "右键单击菜单选项" 无法在 firebug 中进行检查。所以无法在 Firebug> 布局中获取偏移量。 - Monika Yadav
是的,我了解你的问题。即使我也不确定我们如何找到右键单击后获得的选项的宽度。你可以尝试一些试探性的方法,例如逐步增加5或10。告诉我结果如何? - Hari Reddy

0

这是我如何在右键菜单中点击第四个元素的方法。

 Actions myAction = new Actions(driver); 
 myAction.contextClick(driver.findElement(By.xpath("//ul/li[1]/a/img"))).build().perform();
 myAction.sendKeys(Keys.ARROW_DOWN).build().perform();
 myAction.sendKeys(Keys.ARROW_DOWN).build().perform();
 myAction.sendKeys(Keys.ARROW_DOWN).build().perform();
 myAction.sendKeys(Keys.ARROW_DOWN).build().perform();
 myAction.sendKeys(Keys.ENTER).build().perform();

希望这能有所帮助。

0

这是右键单击网页元素的代码。

Actions actions = new Actions(driver);    
Action action=actions.contextClick(WebElement).build(); //pass WebElement as an argument
            action.perform();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接