get StaleElementReferenceException error while usi

2019-06-11 08:22发布

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条回答
beautiful°
2楼-- · 2019-06-11 08:34

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楼-- · 2019-06-11 08:36

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);
} 
查看更多
登录 后发表回答