繁体   English   中英

使用 webdriver selenium 处理子菜单项

[英]handling submenu item with webdriver selenium

我想使用默认情况下不可见的 selenium webdriver 单击子菜单项。 它在 mousehover 上变得可见。 我尝试了一些代码,它给出了如下所示的错误

Caused by: org.openqa.selenium.remote.ErrorHandler$UnknownServerException: Element is not currently visible and so may not be interacted with.

这里的代码:

    Actions actions = new Actions(driver); 
    WebElement menuHoverLink = driver.findElement(By.linkText("RENT")); 
    //WebElement menuHoverLink = driver.findElement(By.className("current")); 
    actions.moveToElement(menuHoverLink); 
    WebElement subLink = driver.findElement(By.cssSelector("a[href='nemc.com/rentals/easy-rent']")); 
    actions.moveToElement(subLink); 
    actions.click(); 
    actions.perform();    

使用Actions类将鼠标悬停在菜单项上,然后单击子菜单选项。 您可以参考 Actions 类来获得可用方法的概述,并在此处很好地帮助您了解如何使用这些交互。

Actions actions = new Actions(driver); WebElement menuHoverLink = driver.findElement(By.linkText("RENT"));
actions.moveToElement(menuHoverLink).perform();
driver.findElement(By.cssSelector("a[href='nemc.com/rentals/easy-rent']")).click();

我希望你的 locatros 是正确的..你可能想使用 [contains(@href,'nemc.com/rentals')'

尝试使用以下代码。 它应该可以工作。尝试将 perform() 添加到您的 moveToElement 语句中,如下所示。

Actions actions = new Actions(driver);
WebElement menuHoverLink = driver.findElement(By.linkText("RENT"));

actions.moveToElement(menuHoverLink).perform();
WebElement subLink = driver.findElement(By.cssSelector("a[href='nemc.com/rentals/easy-rent']"));
sublink.click();

在某些应用程序中, Action交互可能不起作用。 我个人遇到了这个问题,然后我使用了以下解决方案。 我从 selenium 问题跟踪器页面获取了这个解决方案。

 WebElement targetElement = driver.findElement(By.id("locator"));  
 JavascriptExecutor js = (JavascriptExecutor) driver;  
 String mouseOverScript = "if(document.createEvent){var evObj = document.createEvent('MouseEvents');evObj.initEvent('mouseover', true, false); arguments[0].dispatchEvent(evObj);} else if(document.createEventObject) { arguments[0].fireEvent('onmouseover');}";  
 js.executeScript(mouseOverScript, targetElement);  
 driver.findElement(By.id("Click locator")).click;

我最近偶然发现了一个类似的问题, phantomJSghostdriver 就我而言,问题在于窗口大小 - HTML 元素在可见区域之外,我的鼠标移动没有任何影响(默认大小为 400x300,相当小)。

您可以检查窗口大小

driver.manage().window().getSize()

你可以改变它

driver.manage().window().setSize(new Dimension(width, height));

谢谢niharika_neo,

您的代码示例对我来说效果很好。

我确实在主菜单上执行了动作action.moveToElement(mainMenu).perform();

然后找到子菜单项并执行单击操作

driver.findElement(By.xpath(“ // * [@ id =” subMenu]“))。click()

并在加载页面上完成了其余的验证。 恭喜您。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM