ElementReferenceException:过时的元素引用:元素未附加到页面文档

ElementReferenceException: stale element reference: element is not attached to the page document

我要测试硒化物:

@Test
public void Test(){
    open("https://market.yandex.ru/catalog--smartfony/54726/list?hid=91491&glfilter=7893318%3A153043&glfilter=4940921%3A13475069&onstock=1&local-offers-first=0");
    new AfterPhonesCategory()
    .collectResults();
}

我有一个获取产品名称和 return 硒元素的方法,当产品 运行 出来时,我们转到下一页并再次获取元素,直到它们 运行输出:

public class AfterPhonesCategory {

    public List<String> collectResultsFromPage() {

        List<SelenideElement> resultsNameWebElement = $$x("//article//h3[@data-zone-name = 'title']//span");

        Assertions.assertTrue(resultsNameWebElement.stream().anyMatch(x->x.getText().contains("Apple")),
                "the snippet does not contain the name of the apple");

        return resultsNameWebElement.stream() //line 34
                .map(SelenideElement::getText)
                .collect(Collectors.toList());

    }

    private boolean initNextPageButton() {
        List<SelenideElement> goNextPageButton = $$x("//a[contains(@class, '_3OFYT')]");
        if(goNextPageButton.size() > 0){
            goNextPageButton.get(0).click();
            return true;
        }
        else
            return false;
    }


    private List<String> findResults;

    public AfterPhonesCategory collectResults() {
        findResults = collectResultsFromPage();
        while (initNextPageButton()) {   //line 52
            findResults.addAll(collectResultsFromPage());
        }
        return this;
    }

但是在执行代码时出现错误:

    Caused by: org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
at pages.AfterPhonesCategory.collectResultsFromPage(AfterPhonesCategory.java:34)
    at pages.AfterPhonesCategory.collectResults(AfterPhonesCategory.java:52)

我做错了什么?

StaleElementReferenceException 仅当您的元素在您的网站中不存在(消失或未构建)时才会发生。请添加等待条件以检查元素的可见性。

By optionXpath = By.xpath("your xpath fp goes here !");
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(optionXpath));
wait.until(ExpectedConditions.visibilityOfElementLocated(optionXpath));
driver.findElement(optionXpath).click();

未构建的情况 :

you need to add wait conditions

如果消失 :

yours actions on element is wrong. add screenshot just before your failure code and recheck your code.