如何等到Selenium中存在元素?

Ste*_*ers 51 java selenium predicate wait selenium-webdriver

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

fluentWait.until(ExpectedConditions.presenceOfElement(By.id("elementId"));
Run Code Online (Sandbox Code Playgroud)

如果它有帮助,这里是fluentWait:

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

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

Pet*_*sik 65

ignoringWebDriver等待的时候,您需要调用异常来忽略.

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

有关详细信息,请参阅FluentWait的文档.但请注意,此条件已在ExpectedConditions中实现,因此您应该使用

WebElement element = (new WebDriverWait(driver, 10))
   .until(ExpectedConditions.elementToBeClickable(By.id("someid")));
Run Code Online (Sandbox Code Playgroud)

等待的基本教程可以在这里找到.


小智 8

WebDriverWait wait = new WebDriverWait(driver,5)
wait.until(ExpectedConditions.visibilityOf(element));
Run Code Online (Sandbox Code Playgroud)

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