本文介绍了在硒循环中使用driver.navigate().back()时收到StaleElementReferenceException错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,该代码获取元素列表,然后在使用driver.navigate().back();

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

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

On the second round of the loop I get the following error when using the chromedriver

并且我在FirefoxDriver中遇到以下错误

and I get the following error with the FirefoxDriver

driver.navigate().back();不能在上述循环中使用吗?

Can the driver.navigate().back(); not be used inside a loop as above?

推荐答案

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

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

这篇关于在硒循环中使用driver.navigate().back()时收到StaleElementReferenceException错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 16:51