get StaleElementReferenceException error while using driver.navigate().back() in a loop in selenium

无人久伴 提交于 2019-12-10 12:19:58

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/38366251/get-staleelementreferenceexception-error-while-using-driver-navigate-back-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!