I have the following code, which gets a list of elements and then loops through it while using driver.navigate().back();
List<WebElement> listingWebElementList = driver.findElements(By.xpath("(//span[@id='titletextonly'])"));
for (WebElement listingElement : listingWebElementList)
{
Thread.sleep(5000);
listingElement.click();
Thread.sleep(5000);
driver.navigate().back();
}
On the second round of the loop I get the following error when using the chromedriver
org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
and I get the following error with the FirefoxDriver
org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up
Can the driver.navigate().back();
not be used inside a loop as above?
When the DOM hass changed or refreshed the 'driver' losses all the
WebElements
it previously located. You need to relocate the list each iteration of the loopYou can keep tracking the position in the list using indexes.
your problem occurs because when u navigate back again, that element is no longer valid. To avoid this kind of situation, use the below code: