我有网址列表,我只是想在同一个浏览器会话中打开网址。为此,我编写了以下代码,但是在打开第一个URL后抛出错误,即第二个URL未被打开。
findElements = driver.findElements(By.xpath("//*[@id='search-user-found']//p/a"));
for (WebElement webElement : findElements)
{
Thread.sleep(200);
System.out.println(webElement.getAttribute("href"));
driver.navigate().to(webElement.getAttribute("href"));
Thread.sleep(200);
}
错误:
Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up
请协助。
答案 0 :(得分:0)
当您导航到另一个页面时,DOM正在发生变化,而WebDriver
正在丢失之前定位的元素。这会导致StaleElementReferenceException
。我建议你将链接保存为字符串并使用它们。
List<WebElement> findElements = driver.findElements(By.xpath("//*[@id='search-user-found']//p/a"));
List<String> hrefs = new List<String>();
for (WebElement webElement : findElements)
{
hrefs.add(webElement.getAttribute("href"));
}
for (String href : hrefs)
{
Thread.sleep(200);
System.out.println(href);
driver.navigate().to(href);
Thread.sleep(200);
}