Reputation: 8985
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?
Upvotes: 0
Views: 1491
Reputation: 3004
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:
List<WebElement> listingWebElementList = driver.findElements(By.xpath("(//span[@id='titletextonly'])"));
int size = listingWebElementList.size();
for (int i=0;i<size;i++)
{
List<WebElement> listingWebElementListInLoop = driver.findElements(By.xpath("(//span[@id='titletextonly'])"));
Thread.sleep(5000);//don't use this kind of wait. wait using until.
listingWebElementListInLoop.get(i).click();
Thread.sleep(5000);
driver.navigate().back();
Thread.sleep(2000);
}
Upvotes: 3
Reputation: 50819
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 loop
int size = 1;
for (int i = 0 ; i < size ; ++i) {
List<WebElement> listingWebElementList = driver.findElements(By.xpath("(//span[@id='titletextonly'])"));
size = listingWebElementList.size();
Thread.sleep(5000);
listingWebElementList.get(i).click();
Thread.sleep(5000);
driver.navigate().back();
}
You can keep tracking the position in the list using indexes.
Upvotes: 4