Selenium: Waiting for an element do disappear

Christoph Zabinski picture Christoph Zabinski · Jul 2, 2014 · Viewed 28.6k times · Source

I posed with a difficult task. I am fairly new to selenium and still working through the functionalities of waiting for elements and alike.

I have to manipulate some data on a website and then proceed to another. Problem: the manipulation invokes a script that makes a little "Saving..." label appear while the manipulated data is being processed in the background. I have to wait until I can proceed to the next website.

So here it is: How do i wait for and element to DISAPPEAR? Thing is: It is always present in the DOM but only made visible by some script (I suppose, see image below). The palish code contains the said element

This is what I tried but it just doesn't work - there is no waiting, selenium just proceeds to the next step (and gets stuck with an alert asking me if I want to leave or stay on the page because of the "saving...").

private By savingLableLocator = By.id("lblOrderHeaderSaving");

    public boolean waitForSavingDone(By webelementLocator, Integer seconds){
    WebDriverWait wait = new WebDriverWait(driver, seconds);
    Boolean element = wait.until(ExpectedConditions.invisibilityOfElementLocated(webelementLocator));
    return element;
}

UPDATE / SOLUTION:

I came up ith the following solution: I built my own method. Basically it checks in a loop for the CssValue to change.

the loops checks for a certain amount of time for the CSSVALUE "display" to go from "block" to another state.

public void waitForSavingOrderHeaderDone(Integer _seconds){
    WebElement savingLbl = driver.findElement(By.id("lblOrderHeaderSaving"));   
    for (int second = 0;; second++) {
        if (second >= _seconds)
            System.out.println("Waiting for changes to be saved...");
        try {
            if (!("block".equals(savingLbl.getCssValue("display"))))
                break;
        } catch (Exception e) {

        }
    }

Answer

TheFreddyKilo picture TheFreddyKilo · Apr 25, 2016

You can wait for a WebElement to throw a StaleElementReferenceException like this:

public void waitForInvisibility(WebElement webElement, int maxSeconds) {
    Long startTime = System.currentTimeMillis();
    try {
        while (System.currentTimeMillis() - startTime < maxSeconds * 1000 && webElement.isDisplayed()) {}
    } catch (StaleElementReferenceException e) {
        return;
    }
}

So you would pass in the WebElement you want to wait for, and the max amount of seconds you want to wait.