Home > Software design >  Create a loop to reload page while execution using Selenium and Java
Create a loop to reload page while execution using Selenium and Java

Time:02-15

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.

CodePudding user response:

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.

CodePudding user response:

The simplest approach would be to wrap up the code block for continous execution within a try-catch{} block inducing WebDriverWait for the visibilityOfElementLocated() as follows:

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;

try  
{  
    WebElement element = new WebDriverWait(driver, Duration.ofSeconds(20)).until(ExpectedConditions.visibilityOfElementLocated(By.id("elementID")));
    // other lines of code of continius execution
}  
catch(TimeoutException e)  
{  
    driver.navigate().refresh();  
} 
  • Related