How to avoid “StaleElementReferenceException” in Selenium?

前端 未结 16 2381
一向
一向 2020-11-22 12:12

I\'m implementing a lot of Selenium tests using Java. Sometimes, my tests fail due to a StaleElementReferenceException. Could you suggest some approaches to mak

16条回答
  •  忘掉有多难
    2020-11-22 12:46

    Kenny's solution is good, however it can be written in a more elegant way

    new WebDriverWait(driver, timeout)
            .ignoring(StaleElementReferenceException.class)
            .until((WebDriver d) -> {
                d.findElement(By.id("checkoutLink")).click();
                return true;
            });
    

    Or also:

    new WebDriverWait(driver, timeout).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.elementToBeClickable(By.id("checkoutLink")));
    driver.findElement(By.id("checkoutLink")).click();
    

    But anyway, best solution is to rely on Selenide library, it handles this kind of things and more. (instead of element references it handles proxies so you never have to deal with stale elements, which can be quite difficult). Selenide

提交回复
热议问题