我想使用selenium webdriver单击子菜单项,这是默认不可见的。 它在鼠标悬停时变得可见。 我尝试了一些代码,它给出了错误,如下所示
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();
答案 0 :(得分:2)
使用Actions类在菜单项上执行鼠标悬停,然后单击子菜单选项。您可以参考Actions类来概述可用的方法,并获得一个很好的帮助here来了解如何使用这些交互。
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 / rental')'
答案 1 :(得分:0)
尝试使用以下代码。它应该工作。尝试将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();
答案 2 :(得分:0)
在某些应用中,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;
答案 3 :(得分:0)
我最近遇到了phantomJS和ghostdriver的类似问题。就我而言,问题是窗口大小 - HTML元素在可见区域之外,我的鼠标移动没有效果(默认大小为400x300,相当小)。
您可以使用
检查窗口大小driver.manage().window().getSize()
你可以用
改变它driver.manage().window().setSize(new Dimension(width, height));