简体   繁体   中英

Wait for a page to fully load in Selenium

I am using selenium with Java. I want to wait for page to load fully before doing any action on that page.

I have tried the following method, but it is failing to work as expected.

public void waitForElementToBeVisible(final WebElement element) {

    WebDriverWait wait = new WebDriverWait(WebDriverFactory.getWebDriver(), WEBDRIVER_PAUSE_TIME);

    wait.until(ExpectedConditions.visibilityOf(element));

WebDriverWait inherits methods like wait until .

So something like

webDriverWait.until(ExpectedConditions.visibilityOfElementLocated( elementLocator)

should work. You can use ExpectedConditions , it would make things simpler. You can also use the method visibilityOfAllElements

This method will wait until element is visible. Firstly this method will check, whether element is available in html and whether it's display.. it will wait until element will display..

public void E_WaitUntilElementDisplay() throws Exception
{
    int i=1;
    boolean eleche,eleche1 = false; 
    while(i<=1)
    {
            try{
                eleche = driver.findElements(by.xpath("path")).size()!=0;
            }catch(InvalidSelectorException ISExcep)
            {
                eleche = false;
            }
            if(eleche == true)
            {

                while(i<=1)
                {
                    try{
                        eleche1=driver.findElement(By.xpath("Path")).isDisplayed();
                    }catch(org.openqa.selenium.NoSuchElementException NSEE){
                        eleche1=false;
                    }
                    if(eleche1 == true)
                    {
                        i=2;
                        System.out.println("\nElement Displayed.");
                    }
                    else
                    {
                        i=1;
                        Thread.sleep(1500);
                        System.out.println("\nWaiting for element, to display.");
                    }
                }
            }
            else
            {
                i=1;
                Thread.sleep(1500);
                System.out.println("\nWaiting for element, to display.");
            }
    }
}


As another option maybe you can try something like:

if(element.isDisplayed() && element.isEnabled()){
   //your code here 
}

or if you know how long you want to wait:

thread.sleep(3000); //where 3000 is time expression in milliseconds, in this case 3 secs

You can use this function in java to verify whether the page is fully loaded or not. The verification happens two-fold. One using the javascript document.readystate and imposing a wait time on javascript.

/* Function to wait for the page to load. otherwise it will fail the test*/
public void waitForPageToLoad() {
    ExpectedCondition<Boolean> javascriptDone = new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver d) {
            try {
                return ((JavascriptExecutor) getDriver()).executeScript("return document.readyState").equals("complete");
            } catch (Exception e) {
                return Boolean.FALSE;
            }
        }
    };
    WebDriverWait wait = new WebDriverWait(getDriver(), waitTimeOut);
    wait.until(javascriptDone);
}

This works for me:

wait.until(ExpectedConditions.not(
ExpectedConditions.presenceOfElementLocated(
By.xpath("//div[contains(text(),'Loading...')]"))));

Here is the ultimate solution specifically when you are dealing with Angular 7 or 8.

Instead of waiting for a longer duration using sleep or implicit wait methods, you can divide your wait time into the partition and use it recursively.

Below logic will wait for the page to render for a minimum of 300 seconds and a maximum of 900 seconds.

/**
 * This method will check page loading
 *
 */
public void waitForLoadingToComplete() {
    waitLoadingTime(3); // Enter the number of attempts you want to try
}

 private void waitLoadingTime(int i) {
        try {
  // wait for the loader to appear after particular action/click/navigation
            this.staticWait(300); 
  // check for the loader and wait till loader gets disappear
            waitForElementToBeNotPresent(By.cssSelector("Loader Element CSS"));                                                             
        } catch (org.openqa.selenium.TimeoutException e) {
            if (i != 0)
                waitLoadingTime(i - 1);
        }
    }

/**
 * This method is for the static wait
 *
 * @param millis
 */
public void staticWait(final long millis) {
    try {
        TimeUnit.MILLISECONDS.sleep(millis);
    } catch (final InterruptedException e) {
        System.err.println("Error in staticWait." + e);
    }
}

public void waitForElementToBeNotPresent(final By element) {
    long s = System.currentTimeMillis();
    new WebDriverWait(this.getDriver(), 30)
            .until(ExpectedConditions.not(ExpectedConditions.presenceOfAllElementsLocatedBy(element)));
    System.err.println("Waiting for Element to be not present completed. " + (System.currentTimeMillis() - s));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM