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


当前回答

对于存在的任何元素使用if条件和

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

其他回答

使用类WebDriverWait

也可以看这里

您可以期望显示一些元素。类似于c#:

WebDriver _driver = new WebDriver();
WebDriverWait _wait = new WebDriverWait(_driver, new TimeSpan(0, 1, 0));

_wait.Until(d => d.FindElement(By.Id("Id_Your_UIElement")));

我的方法很简单:

long timeOut = 5000;
    long end = System.currentTimeMillis() + timeOut;

        while (System.currentTimeMillis() < end) {

            if (String.valueOf(
                    ((JavascriptExecutor) driver)
                            .executeScript("return document.readyState"))
                    .equals("complete")) {
                break;
            }
        }

对于隐式等待,你可以使用如下代码:

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS)

为了使网页等待一个特定的对象是可见的或某些条件是真实的。您可以使用网页驱动程序等羽。

//120 is maximum number of seconds to wait.
WebDriverWait wait = new WebDriverWait(driver,120);  
wait.until(ExpectedConditions.elementToBeClickable("CONDITITON"));

在Java中,另一种选择是让线程在特定的时间内休眠。

Thread.sleep(numberOfSeconds*1000); 
//This line will cause thread to sleep for seconds as variable

我创建了一个方法来简化线程。睡眠的方法

public static void wait_time(int seconds){
    try {
        Thread.sleep(seconds*1000);
        }catch (InterruptedException e) {
        // TODO Auto-generated catch block
            e.printStackTrace();
        }
}

使用wait_time(10)方法;线程将休眠10秒。

public static int counter = 0;

public void stepGeneralWait() {

    boolean breakIt = true;

    while (true) {
        breakIt = true;
        try {

            do{
                // here put e.g. your spinner ID
                Controller.driver.findElement(By.xpath("//*[@id='static']/div[8]/img")).click();
                Thread.sleep(10000);

                counter++;

                if (counter > 3){
                    breakIt = false;

                }
            }
            while (breakIt);



        } catch (Exception e) {
            if (e.getMessage().contains("element is not attached")) {
                breakIt = false;
            }
        }
        if (breakIt) {
            break;
        }

    }

    try {
        Thread.sleep(12000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

在python中,你可以简单地使用:

driver.implicitly_wait(30)