Search code examples
javaseleniumselenium-webdrivertry-catchwebdriverwait

Create a loop to reload page while execution using Selenium and Java


I have a page that in certain moments, it doesn't load in selenium. If I clicking in 'Reload' button on page that selenium opening, sometimes the page load. This page is a legacy system and e we cannot change it.

Then I need to create a condition, like this:

  • If Id:xxx is visible

    • continius execution
  • If doesn't:

    • driver.navigate().refresh();

I'm using Selenium Java.


Solution

  • I would suggest to implement a custom ExpectedCondition, like:

    import org.openqa.selenium.support.ui.ExpectedCondition
    
    public static ExpectedCondition<Boolean> elementToBeVisibleWithRefreshPage(By element, int waitAfterPageRefreshSec) {
        return new ExpectedCondition<Boolean>() {
            private boolean isLoaded = false;
    
            @Override
            public Boolean apply(WebDriver driver) {
                List elements = driver.findElements(element);
                if(!elements.isEmpty()) {
                    isLoaded = elements.get(0).isDisplayed();
                }
                if(!isLoaded) {
                    driver.navigate().refresh();
                    // some sleep after page refresh
                    Thread.sleep(waitAfterPageRefreshSec * 1000);
                }
                return isLoaded;
            }
        };
    
    }
    

    Usage:

    By element = By.id("xxx");
    
    new WebDriverWait(driver, Duration.ofSeconds(30)).until(elementToBeVisibleWithRefreshPage(element, 10));
    

    This will wait for 30 sec, until the element will be visible and will refresh the page with 10 sec pause, if the element wasn't visible.

    Potentially sleep might be replaced with some other WebDriver wait, but this should also work.