问题
I want to click submenu item using selenium webdriver which is invisible bydefault. It becomes visible on mousehover . I tried with some code and it is giving error as shown below
Caused by: org.openqa.selenium.remote.ErrorHandler$UnknownServerException: Element is not currently visible and so may not be interacted with.
Here the code:
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();
回答1:
Use the Actions class to do a mousehover on your menu item and then a click on the submenu option. You can refer to Actions class to get an overview of the methods available and a good help here to understand how to use these interactions.
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();
I am hoping your locatros are correct..you might want to use a[contains(@href,'nemc.com/rentals')'
回答2:
In some applications the Action
interactions may not work. Personally i faced the problem and then i used the below solution. I took this solution from selenium issue tracker page.
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:
Try using the below code. It should work.Try adding perform() to your moveToElement statement as shown below.
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();
回答4:
I stumbled across a similar issue recently, with phantomJS and ghostdriver. In my case, the problem was the window size - the HTML element was outside the visible area and my mouse movements were having no effect (default size is 400x300, which is rather small).
You can check the window size with
driver.manage().window().getSize()
And you can change it with
driver.manage().window().setSize(new Dimension(width, height));
来源:https://stackoverflow.com/questions/16160997/handling-submenu-item-with-webdriver-selenium