如何让Selenium 2.0等待页面加载?


当前回答

您可以删除系统。线。添加它是为了调试目的。

WebDriver driver_;

public void waitForPageLoad() {

    Wait<WebDriver> wait = new WebDriverWait(driver_, 30);
    wait.until(new Function<WebDriver, Boolean>() {
        public Boolean apply(WebDriver driver) {
            System.out.println("Current Window State       : "
                + String.valueOf(((JavascriptExecutor) driver).executeScript("return document.readyState")));
            return String
                .valueOf(((JavascriptExecutor) driver).executeScript("return document.readyState"))
                .equals("complete");
        }
    });
}

其他回答

private static void checkPageIsReady(WebDriver driver) {
    JavascriptExecutor js = (JavascriptExecutor) driver;

    // Initially bellow given if condition will check ready state of page.
    if (js.executeScript("return document.readyState").toString().equals("complete")) {
        System.out.println("Page Is loaded.");
        return;
    }

    // This loop will rotate for 25 times to check If page Is ready after
    // every 1 second.
    // You can replace your value with 25 If you wants to Increase or
    // decrease wait time.
    for (int i = 0; i < 25; i++) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
        // To check page ready state.
        if (js.executeScript("return document.readyState").toString().equals("complete")) {
            break;
        }
    }
}

如果有人使用硒化物:

public static final Long SHORT_WAIT = 5000L; // 5 seconds
$("some_css_selector").waitUntil(Condition.appear, SHORT_WAIT);

更多条件可以在这里找到: http://selenide.org/javadoc/3.0/com/codeborne/selenide/Condition.html

使用这个函数

public void waitForPageLoad(ChromeDriver d){
        String s="";
        while(!s.equals("complete")){
        s=(String) d.executeScript("return document.readyState");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        }

    }

The best way to wait for page loads when using the Java bindings for WebDriver is to use the Page Object design pattern with PageFactory. This allows you to utilize the AjaxElementLocatorFactory which to put it simply acts as a global wait for all of your elements. It has limitations on elements such as drop-boxes or complex javascript transitions but it will drastically reduce the amount of code needed and speed up test times. A good example can be found in this blogpost. Basic understanding of Core Java is assumed.

http://startingwithseleniumwebdriver.blogspot.ro/2015/02/wait-in-page-factory.html

所有这些解决方案在特定情况下都是可行的,但它们至少会遇到以下几个问题中的一个:

它们不够通用——它们想让你提前知道,你要访问的页面的某些特定条件将是真的(例如某些元素将被显示)。 它们会出现竞态条件,即您使用的元素实际上同时出现在旧页面和新页面上。

下面是我尝试的避免这个问题的通用解决方案(在Python中):

首先,一个通用的“等待”函数(如果你喜欢,可以使用WebDriverWait,我觉得它们很丑):

def wait_for(condition_function):
    start_time = time.time()
    while time.time() < start_time + 3:
        if condition_function():
            return True
        else:
            time.sleep(0.1)
    raise Exception('Timeout waiting for {}'.format(condition_function.__name__))

接下来,解决方案依赖于这样一个事实,即selenium为页面上的所有元素记录了一个(内部的)id-number,包括顶级的<html>元素。当页面刷新或加载时,它会获得一个带有新ID的新html元素。

假设你想点击一个文本为“my link”的链接,例如:

old_page = browser.find_element_by_tag_name('html')

browser.find_element_by_link_text('my link').click()

def page_has_loaded():
    new_page = browser.find_element_by_tag_name('html')
    return new_page.id != old_page.id

wait_for(page_has_loaded)

对于更多python化的、可重用的、通用的helper,你可以创建一个上下文管理器:

from contextlib import contextmanager

@contextmanager
def wait_for_page_load(browser):
    old_page = browser.find_element_by_tag_name('html')

    yield

    def page_has_loaded():
        new_page = browser.find_element_by_tag_name('html')
        return new_page.id != old_page.id

    wait_for(page_has_loaded)

然后你可以在几乎任何硒相互作用中使用它:

with wait_for_page_load(browser):
    browser.find_element_by_link_text('my link').click()

我想那是防弹的!你怎么看?

更多信息在这里关于它的博客文章