Selenium: dealing with intermittent cases of element not found



  • Sometimes it works and sometimes it doesn't.

    I've tried implicit wait:

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

    I've tried explicit wait:

        wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(ElementNames.CITYSEARCH_FIELD))).sendKeys(city);
    

    Both don't seem to guarantee that my tests work 10/10 times. Is there a way to actually deal with something like this?

    I've also tried something like this:

        ...
        while(attempts < 2) {
            try {
                selector.selectByVisibleText(choice);
                result = true;
                break;
            } catch(StaleElementReferenceException e) {
    
        }
        attempts++;
    }
    return result;
    

    This method works on a more consistent basis compared to implicit/explicit wait. But still fails maybe once or twice depending on how long the tests are (e.g going through files with 200,000 lines and performing actions for each line)

    Does anyone have any possible suggestion/solution?



  • Try writing a method that you can reuse whenever you want to find a new web element, but that will timeout after a specific time.

    You want to try/catch all the WebDriver exceptions, not just Stale Element. Make sure to include a sleep time in the catch, or else the test will retry like crazy whenever a try fails.

    Here is an example:

    public static WebElement getElementByLocator(final String elementName, final By locator, final int waitTime)
    {
        final long startTime = System.currentTimeMillis();
        boolean found = false;
        WebElement we = null;
        while( (System.currentTimeMillis() - startTime) < 20000 )
        {
            try {
                we = wait.until(ExpectedConditions.presenceOfElementLocated(locator));
                found = true;
                break;
            } catch ( WebDriverException e) {
                log.error("Exception when trying to find element: " + elementName + "\n", e);
                Thread.sleep(waitTime);
            }
        }
        long endTime = System.currentTimeMillis();
        long totalTime = endTime - startTime;
        if (found) {
            log.info("Successfully found the element: " + elementName + " - waited for: " + totalTime + " ms");
            Thread.sleep(waitTime);
        } else {
            log.error("COULD NOT FIND THE ELEMENT: " + elementName + " - after waiting for: " + totalTime + " ms");
            fail("TEST CASE FAILED ON: " + elementName);
        }
        return we;
    }
    


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2