Search code examples
javaselenium-webdriverwait

Element not visible exception - even if different Selenium waits are used


I am trying to automate functional testing of a web application using Selenium and Java. In my application there are several menus. When clicked on a particular menu, a drop down of sub menus appear click to view screenshot of menu

I use below code to click sub menu

driver.findElement(By.xpath("id=menu")).click();
driver.findElement(By.xpath("id=sub_menu_a")).click();

but the issue is that it throws a 'ElementNotVisibleException' at the second line. The same happens even if I use implicit wait

driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

explicit wait

WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("id=sub_menu_a")));

and fluent wait.

Wait<WebDriver> fluentWait=new FluentWait<WebDriver>(driver)
                .withTimeout(60, TimeUnit.SECONDS)
                .pollingEvery(2, TimeUnit.SECONDS)
                .ignoring(NoSuchElementException.class,ElementNotVisibleException.class);
        WebElement element=fluentWait.until(new Function<WebDriver, WebElement>() {
            public WebElement apply(WebDriver driver){
                driver.findElement(By.xpath("id=menu"));
                return driver.findElement(By.xpath("id=sub_menu_a"));
            }
        });
        element.click();

but no luck. But the code works fine if add sleep time using

Thread.sleep(sleeptime);

before and after the first line of code. But it is not a permanent solution since the page load time may vary depend on the network speed and the data in the page. Is there any other solution?


Solution

  • Try this

        WebElement menu=driver.findElement(By.xpath("id=menu"));
        JavascriptExecutor executor = (JavascriptExecutor)driver;
        executor.executeScript("arguments[0].click();", menu);
        WebElement subMenu=driver.findElement(By.xpath("id=sub_menu_a"));
        executor.executeScript("arguments[0].click();", subMenu);
    

    Hope this work