简体   繁体   English

等待页面在 Selenium 中完全加载

[英]Wait for a page to fully load in Selenium

I am using selenium with Java.我在 Java 中使用 selenium。 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 . WebDriverWait继承了诸如 wait until 之类的方法。

So something like所以像

webDriverWait.until(ExpectedConditions.visibilityOfElementLocated( elementLocator)

should work.应该管用。 You can use ExpectedConditions , it would make things simpler.您可以使用ExpectedConditions ,它会使事情变得更简单。 You can also use the method visibilityOfAllElements您还可以使用方法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..首先这个方法会检查元素在html中是否可用以及它是否显示..它会等到元素显示..

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.你可以在java中使用这个函数来验证页面是否完全加载。 The verification happens two-fold.验证发生两方面。 One using the javascript document.readystate and imposing a wait time on javascript.一种使用 javascript document.readystate 并在 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.这是您处理 Angular 7 或 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.下面的逻辑将等待页面呈现最少 300 秒和最多 900 秒。

/**
 * 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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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