Issue
I have a test for 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();
}
I have a methods which get the product names and return the selenide elements, when the product runs out, we go to the next page and also get the elements again until they run out:
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;
}
but when executing the code I get an error:
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)
What am I doing wrong?
Solution
StaleElementReferenceException will be occurs only when your element is not present(vanished or not constructed till) in your website. please add wait conditions to check the visiblity of the element.
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();
In case of not constructed :
you need to add wait conditions
In case of vanished :
yours actions on element is wrong. add screenshot just before your failure code and recheck your code.
Answered By - Jayanth Bala