【问题标题】:Element not found in cache - Selenium在缓存中找不到元素 - Selenium
【发布时间】:2016-02-02 17:22:54
【问题描述】:

我有 URL 列表,我只是想在同一个浏览器会话中打开 URL。为此,我编写了以下代码,但在打开第一个 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

请帮忙。

【问题讨论】:

标签: java selenium-webdriver


【解决方案1】:

当您导航到另一个页面时,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);
}

【讨论】:

    猜你喜欢
    • 2016-04-18
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多