ElementReferenceException:过期元素引用:元素没有附加到页面文档



我对Selenide进行了测试:

@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();
}

我有一个获取产品名称并返回硒元素的方法,当产品用完时,我们转到下一页并再次获取元素,直到它们用完:

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();

如果没有构造:

您需要添加等待条件

如果消失了:

你在元素上的动作是错误的。在失败代码和之前添加截图重新检查你的代码

最新更新