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


当前回答

如果有人使用硒化物:

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 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();
    }

}

你也可以使用类:ExpectedConditions来显式地等待一个元素出现在网页上,然后你才能采取任何行动

你可以使用ExpectedConditions类来确定一个元素是否可见:

WebElement element = (new WebDriverWait(getDriver(), 10)).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input#houseName")));

查看ExpectedConditions类Javadoc,了解您可以检查的所有条件的列表。

在Webdriver/Selenium 2软件测试工具中有两种类型的等待。一种是隐式等待,另一种是显式等待。两者(隐式等待和显式等待)在WebDriver中都很有用。使用等待,我们告诉WebDriver在进入下一步之前等待一定的时间。可以使用隐式等待来等待页面加载。

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

使用隐式等待等待页面上的每个元素直到给定的时间。

driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

这将等待页面上的每个元素30秒。

另一种等待是显式等待或有条件等待,在这个等待直到给定条件。

WebDriverWait wait = new WebDriverWait(driver, 40);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));

在id中,给出静态元素id,一旦页面加载,它就会不小心显示在页面上。

Use:

driver.manage().timeOuts().implicitlyWait(10, TimeUnit.SECONDS);

这意味着对网页上元素的任何搜索都需要时间来加载。implicitlyWait在抛出异常之前设置。 TimeUnit显示您想要等待的任何方式(秒、分、小时和天)。