Java 如何等到元素出现在 Selenium 中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20903231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:10:45  来源:igfitidea点击:

How to wait until an element is present in Selenium?

javaseleniumselenium-webdriverwaitpredicate

提问by Steve Chambers

I'm trying to make Selenium wait for an element that is dynamically added to the DOM after page load. Tried this:

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

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

In case it helps, here is fluentWait:

如果有帮助,这里是fluentWait

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

But it throws a NoSuchElementException- looks like presenceOfElementexpects the element to be there so this is flawed. This must be bread and butter to Selenium and don't want to reinvent the wheel... could anyone suggest an alternative, ideally without rolling my own Predicate?

但它抛出一个NoSuchElementException- 看起来presenceOfElement希望元素在那里,所以这是有缺陷的。这对 Selenium 来说必须是面包和黄油,并且不想重新发明轮子……有人可以提出替代方案,最好不要自己动手Predicate吗?

采纳答案by Petr Mensik

You need to call ignoringwith exception to ignore while the WebDriverwill wait.

您需要调用ignoring异常以忽略而WebDriver将等待。

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

See the documentation of FluentWaitfor more info. But beware that this condition is already implemented in ExpectedConditionsso you should use

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

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

*Update for newer versions of Selenium:

*更新新版本的 Selenium:

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

So the code will look as such:

所以代码看起来像这样:

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

Basic tutorial for waiting can be found here.

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

回答by Andrei Solntsev

Let me recommend you using Selenidelibrary. It allows writing much more concise and readable tests. It can wait for presence of elements with much shorter syntax:

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

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

Here is a sample project for testing Google search: https://github.com/selenide-examples/google

这是一个用于测试 Google 搜索的示例项目:https: //github.com/selenide-examples/google

回答by Ashwini

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;

    }

回答by palandlom

FluentWait throws a NoSuchElementException is case of the confusion

FluentWait 抛出 NoSuchElementException 是混淆的情况

org.openqa.selenium.NoSuchElementException;     

with

java.util.NoSuchElementException

in

.ignoring(NoSuchElementException.class)

回答by bhupendra

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

you can use this as some time before loading whole page code gets executed and throws and error. time is in second

您可以在加载整个页面代码被执行并抛出和错误之前使用它。时间在秒