How to avoid “StaleElementReferenceException” in Selenium?

前端 未结 16 2124
一向
一向 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:57

    The reason why the StaleElementReferenceException occurs has been laid out already: updates to the DOM between finding and doing something with the element.

    For the click-Problem I've recently used a solution like this:

    public void clickOn(By locator, WebDriver driver, int timeout)
    {
        final WebDriverWait wait = new WebDriverWait(driver, timeout);
        wait.until(ExpectedConditions.refreshed(
            ExpectedConditions.elementToBeClickable(locator)));
        driver.findElement(locator).click();
    }
    

    The crucial part is the "chaining" of Selenium's own ExpectedConditions via the ExpectedConditions.refreshed(). This actually waits and checks if the element in question has been refreshed during the specified timeout and additionally waits for the element to become clickable.

    Have a look at the documentation for the refreshed method.

提交回复
热议问题