如何等到Selenium中存在元素?

时间:2014-01-03 12:03:44

标签: java selenium selenium-webdriver wait predicate

我试图让Selenium在页面加载后等待动态添加到DOM的元素。试过这个:

fluentWait.until(ExpectedConditions.presenceOfElement(By.id("elementId"));

如果有帮助,这里是fluentWait

FluentWait fluentWait = new FluentWait<>(webDriver) {
    .withTimeout(30, TimeUnit.SECONDS)
    .pollingEvery(200, TimeUnit.MILLISECONDS);
}

但它抛出一个NoSuchElementException - 看起来presenceOfElement期望元素在那里,所以这是有缺陷的。这对Selenium来说一定是面包和黄油,并且不想重新发明轮子......任何人都可以提出替代方案,理想情况下不要自己动手Predicate吗?

5 个答案:

答案 0 :(得分:59)

ignoring等待时,您需要异常调用WebDriver来忽略。

FluentWait<WebDriver> fluentWait = new FluentWait<>(driver)
        .withTimeout(30, TimeUnit.SECONDS)
        .pollingEvery(200, TimeUnit.MILLISECONDS)
        .ignoring(NoSuchElementException.class);

有关详细信息,请参阅FluentWait的文档。但要注意这个条件已经在ExpectedConditions中实现,所以你应该使用

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

*Update for newer versions of Selenium:

withTimeout(long, TimeUnit) has become withTimeout(Duration)
pollingEvery(long, TimeUnit) has become pollingEvery(Duration)

所以代码看起来像这样:

FluentWait<WebDriver> fluentWait = new FluentWait<>(driver)
        .withTimeout(Duration.ofSeconds(30)
        .pollingEvery(Duration.ofMillis(200)
        .ignoring(NoSuchElementException.class);

可以找到等待的基本教程here

答案 1 :(得分:6)

WebDriverWait wait = new WebDriverWait(driver,5)
wait.until(ExpectedConditions.visibilityOf(element));

你可以在加载整个页面代码执行和抛出错误之前使用它。时间是第二个

答案 2 :(得分:1)

我建议您使用Selenide库。 它允许编写更简洁和可读的测试。它可以等待语法更短的元素存在:

$("#elementId").shouldBe(visible);

以下是测试Google搜索的示例项目: https://github.com/selenide-examples/google

答案 3 :(得分:0)

public WebElement fluientWaitforElement(WebElement element, int timoutSec, int pollingSec) {

    FluentWait<WebDriver> fWait = new FluentWait<WebDriver>(driver).withTimeout(timoutSec, TimeUnit.SECONDS)
        .pollingEvery(pollingSec, TimeUnit.SECONDS)
        .ignoring(NoSuchElementException.class, TimeoutException.class).ignoring(StaleElementReferenceException.class);

    for (int i = 0; i < 2; i++) {
        try {
            //fWait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//*[@id='reportmanager-wrapper']/div[1]/div[2]/ul/li/span[3]/i[@data-original--title='We are processing through trillions of data events, this insight may take more than 15 minutes to complete.']")));
        fWait.until(ExpectedConditions.visibilityOf(element));
        fWait.until(ExpectedConditions.elementToBeClickable(element));
        } catch (Exception e) {

        System.out.println("Element Not found trying again - " + element.toString().substring(70));
        e.printStackTrace();

        }
    }

    return element;

    }

答案 4 :(得分:0)

FluentWait抛出NoSuchElementException是混乱的情况

org.openqa.selenium.NoSuchElementException;     

java.util.NoSuchElementException

in

.ignoring(NoSuchElementException.class)