在硒循环中使用driver.navigate().back()时收到StaleElementReferenceException错误 [英] get StaleElementReferenceException error while using driver.navigate().back() in a loop in selenium
问题描述
我有以下代码,该代码获取元素列表,然后在使用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
org.openqa.selenium.StaleElementReferenceException:过时的元素 参考:元素未附加到页面文档
org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
并且我在FirefoxDriver中遇到以下错误
and I get the following error with the FirefoxDriver
org.openqa.selenium.StaleElementReferenceException:找不到元素 在缓存中-自查找以来,页面可能已更改
org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up
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错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!