Search code examples
javaseleniummouseover

Mouseover Selenium with Java


I have the following problem: I am using the selenium webdriver with Java and want to extract all links of a webpage. Some links are generated on demand. That means with a mouseover on the menulinks there will be generated more links. When I load the page these links are not there.

I tried to first extract the menu-navigation-links, do a mouseover and then ask the driver for the "new" links. But it seems that there a no "new" links.

WebElement mainNavi = element.findElement(By.className("navigation"));

Actions actions = new Actions(driver);
List<WebElement> menuHoverLinks = new ArrayList<WebElement>();
menuHoverLinks.addAll(mainNavi.findElements(By.cssSelector("a")));

for (WebElement menuHoverLink : menuHoverLinks) {
  Actions hoverOverRegistrar = actions.moveToElement(menuHoverLink);
  hoverOverRegistrar.perform();
}

First: Is my idea right? Is it possible to do so? If yes, what am I doing wrong?

Thanks in advance!


Solution

  • If the links are generated dynamically then they may not exist initially. You should use Implicit Waits after you click on the menu to allow the webpage to load up the new content before trying to query them.

    Instead of using Actions, consider using WebElement, which supports clicking.

    For example, You might say something like

    // do an implicit wait until the menu is fully loaded
    List<WebElement> elmts = driver.findElements(By.cssSelector("a"));
    for (WebElement elmt : elmts) {
        elmt.click();
    }