Web table is taking more time to load by the time another element is clicked how to handle the wait in selenium Java

22 Views Asked by At

Managing the delay in loading a web table before clicking another element

The web table exhibits a prolonged loading time, necessitating the implementation of a wait strategy in Selenium (Java) to ensure its complete rendering before proceeding to interact with another element.

public static void saveAndContinues(WebDriver driver) {
    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(60));

    // Wait for the "Continue" button to be clickable
    WebElement continueButton =         wait.until(ExpectedConditions.presenceOfElementLocated(GENERIC_CONTINUE_BUTTON));

    // Check if the table loading indicator is present
    WebElement loadingIndicator = driver.findElement(By.xpath("//*[@id='yourproducts'][2]"));
    if (loadingIndicator.isDisplayed()) {
        // Continue waiting if the table is still loading
        WebDriverWait wait1 = new WebDriverWait(driver, Duration.ofSeconds(30));
        // You can add additional conditions if needed
        throw new RuntimeException("Table is still loading");
    }

    // Click on the "Continue" button
    continueButton.click();
}
1

There are 1 best solutions below

3
Shatas On

I would suggest having a method similar to this one:

    public static void waitForElementToNotBePresent(By locator, int maxTimeout, int waitPeriod) throws InterruptedException {
        int currentTimeout = 0;

        while (currentTimeout < maxTimeout) {
            try {
                // if element is found, it means the loading process is still not finished
                Driver.driver.findElement(locator);
                currentTimeout += waitPeriod;
                Thread.sleep(waitPeriod);
            } catch (NoSuchElementException ex) {
                // if element is not found, the loading process is finished
                return;
            }
        }

        // if we reach this point, the loading process did not finish in the given time
        // otherwise we might end in an infinite loop
        throw new TimeoutException("Loading did not finish in the given time");
    }

It would allow you to have a long wait for the element to disappear but it would also check regularly for it's presence.

With this method your code would look something like this:

waitForElementToNotBePresent(By.xpath("//*[@id='yourproducts'][2]"), 60000, 1000);
continueButton.click();