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


当前回答

driver.asserts().assertElementFound("Page was not loaded",
By.xpath("//div[@id='actionsContainer']"),Constants.LOOKUP_TIMEOUT);

其他回答

你可以显式地等待一个元素出现在网页上,然后才可以采取任何操作(如element.click()):

driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
    .until(new ExpectedCondition<WebElement>() {
        @Override
        public WebElement apply(WebDriver d) {
            return d.findElement(By.id("myDynamicElement"));
        }
    }
);

这是我用于类似场景的方法,效果很好。

NodeJS答案:

在Nodejs中,你可以通过承诺得到它…

如果您编写了这段代码,您可以确保当您到达then…

driver.get('www.sidanmor.com').then(()=> {
    // here the page is fully loaded!!!
    // do your stuff...
}).catch(console.log.bind(console));

如果您编写了这段代码,您将进行导航,selenium将等待3秒……

driver.get('www.sidanmor.com');
driver.sleep(3000);
// you can't be sure that the page is fully loaded!!!
// do your stuff... hope it will be OK...

来自Selenium Documentation (Nodejs):

这一点。get(url)→Thenable<undefined> 调度命令导航到给定的URL。 返回一个承诺,该承诺将在文档完成加载时得到解决。

如果有人使用硒化物:

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

如何让Selenium在单击后等待页面加载提供了以下有趣的方法:

存储旧页面中对WebElement的引用。 点击链接。 继续调用WebElement上的操作,直到抛出StaleElementReferenceException。

示例代码:

WebElement link = ...;
link.click();
new WebDriverWait(webDriver, timeout).until((org.openqa.selenium.WebDriver input) ->
{
    try
    {
        link.isDisplayed();
        return false;
    }
    catch (StaleElementReferenceException unused)
    {
        return true;
    }
});

WebDriver driver = new ff / chrome / anyDriverYouWish(); .timeouts driver.manage()()。TimeUnit.SECONDS implicitlyWait(10日); 最多等待10秒。 WebDriverWait wait = new WebDriverWait(driver, 10); wait.until (ExpectedConditions。visibilityOf (WebElement元素)); FluentWait <司机> FluentWait; fluentWait = new fluentWait <>(driver)。TimeUnit.SECONDS withTimeout(30日) TimeUnit.MILLISECONDS .pollingEvery (200) . ignore (NoSuchElementException.class);

最后一个选项的优点是可以包含预期的异常,以便继续执行。