0

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?

2 Answers 2

4

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.

3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.