Wait for page load in Selenium

后端 未结 30 2988
攒了一身酷
攒了一身酷 2020-11-22 07:12

How do you make Selenium 2.0 wait for the page to load?

30条回答
  •  甜味超标
    2020-11-22 08:09

    I'm surprised that predicates weren't the first choice as you typically know what element(s) you will next interact with on the page you're waiting to load. My approach has always been to build out predicates/functions like waitForElementByID(String id) and waitForElemetVisibleByClass(String className), etc. and then use and reuse these wherever I need them, be it for a page load or page content change I'm waiting on.

    For example,

    In my test class:

    driverWait.until(textIsPresent("expectedText");
    

    In my test class parent:

    protected Predicate textIsPresent(String text){
        final String t = text;
        return new Predicate(){
            public boolean apply(WebDriver driver){
                return isTextPresent(t);
            }
        };
    }
    
    protected boolean isTextPresent(String text){
        return driver.getPageSource().contains(text);
    }
    

    Though this seems like a lot, it takes care of checking repeatedly for you and the interval for how often to check can be set along with the ultimate wait time before timing out. Also, you will reuse such methods.

    In this example, the parent class defined and initiated the WebDriver driver and the WebDriverWait driverWait.

    I hope this helps.

提交回复
热议问题