在硒循环中使用 driver.navigate().back() 时出现 StaleElementReferenceException 错误

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

我有以下代码,它获取元素列表,然后在使用 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();
}

在第二轮循环中,我在使用 chromedriver 时出现以下错误

org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document

我在使用 FirefoxDriver

时收到以下错误

org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up

driver.navigate().back();不能像上面那样在循环中使用吗?

当 DOM 发生变化或刷新时,'driver' 会丢失其先前定位的所有 WebElements。您需要在循环的每次迭代中重新定位列表

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

您可以使用索引跟踪列表中的位置。

出现您的问题是因为当您再次导航回来时,该元素不再有效。为避免这种情况,请使用以下代码:

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