Wait for page load in Selenium

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

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

30条回答
  •  梦如初夏
    2020-11-22 07:56

    /**
     * Call this method before an event that will change the page.
     */
    private void beforePageLoad() {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("document.mpPageReloaded='notYet';");
    }
    
    /**
     * Call this method after an event that will change the page.
     * 
     * @see #beforePageLoad
     * 
     *      Waits for the previous page to disappear.
     */
    private void afterPageLoad() throws Exception {
        (new WebDriverWait(driver, 10)).until(new Predicate() {
    
            @Override
            public boolean apply(WebDriver driver) {
                JavascriptExecutor js = (JavascriptExecutor) driver;
                Object obj = js.executeScript("return document.mpPageReloaded;");
                if (obj == null) {
                    return true;
                }
                String str = (String) obj;
                if (!str.equals("notYet")) {
                    return true;
                }
                return false;
            }
        });
    }
    

    You can change from the document to an element, in the case of where only part of a document is being changed.

    This technique was inspired by the answer from sincebasic.

提交回复
热议问题