【问题标题】:StaleElementReferenceException: stale element reference:StaleElementReferenceException:过时的元素引用:
【发布时间】:2014-12-03 13:28:37
【问题描述】:

我需要从代码中访问folderId:

{
"folderType": 3,
            "createdDate": "02.09.2014 11:57:28.UTC",
            "modifiedDate": "02.09.2014 11:57:28.UTC",
            "folderName": "Enterprise",
            "folderId": "baebc0fb-38cb-4300-9bd1-9b98fa622e4a",
            "widgetType": null,
            "enterpriseId": "366fc1f1-670d-41bc-905e-bc80accd2537",
            "parentFolderId": "",
}
{
"folderType": 3,
            "createdDate": "02.09.2014 11:57:28.UTC",
            "modifiedDate": "02.09.2014 11:57:28.UTC",
            "folderName": "Enter",
            "folderId": "6671ca49-9637-488e-9a0e-f7dbf415a542",
            "widgetType": null,
            "enterpriseId": "366fc1f1-670d-41bc-905e-bc80accd2537",
            "parentFolderId": "",
}

我需要访问'Enterprise'和'Enter'文件夹的folderId。

这是我的代码:

String s1= driver.findElement(By.xpath("//span[. = '\"Enterprise\"']/ancestor::pre/following-sibling::pre[1]/span[2]" )).getText();

String s2=driver.findElement(By.xpath("//span[. = '\"Enter\"']/ancestor::pre/following-sibling::pre[1]/span[2]")).getText();

我想打印不带 cotes 的字符串 s1 和 s2 的值。 我可以访问“企业”文件夹 ID,但无法访问“输入”文件夹 ID。 因为 'Enter' folderId 是新创建的文件夹。

对于出现在 cotes 之间的每个字段,以下是 GENERAL FORAMT HTML 代码:

<pre>            <span class="cm-string">"folderName"</span>: <span class="cm-string">"Enter"</span>,</pre>
<pre>            <span class="cm-string">"folderId"</span>: <span class="cm-string">"6671ca49-9637-488e-9a0e-f7dbf415a542"</span>,</pre>

我可以像这样使用 chrome 开发者工具选择 Enter folderId:

$x("//span[. = '\"Enter\"']/ancestor::pre/following-sibling::pre[1]/span[2]")
[<span class=​"cm-string">​"6671ca49-9637-488e-9a0e-f7dbf415a542"​</span>​]

eclipse中的实际输出: 线程“主”org.openqa.selenium.StaleElementReferenceException 中的异常:过时的元素引用:元素未附加到页面文档 (会话信息:chrome=37.0.2062.124)

【问题讨论】:

  • 你在什么浏览器中测试它?
  • Chrome 浏览器。它是我正在尝试自动化的 chrome 扩展“邮递员休息客户端”。

标签: java selenium xpath selenium-webdriver


【解决方案1】:

StaleElementReferenceException 是由于 findelement() 方法正在访问的元素不可用。

使用下面的示例代码等待元素的可见性:

private static WebElement findElement(WebDriver driver, By locator) {
    Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
            .withTimeout(90, TimeUnit.SECONDS)
            .pollingEvery(5, TimeUnit.SECONDS)
            .ignoring(NoSuchElementException.class, StaleElementReferenceException.class);
    return wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
}

Read more...

【讨论】:

  • 所以我在这里有一个疑问,每当我可以使用 chrome 中的开发人员工具找到元素时,如果它在 eclipse 中仍然不起作用。那可能是什么原因?我多次遇到这样的问题。
  • FluentWait 将解决首先等待元素可见性的问题。抱歉,我对此没有深入的了解。
猜你喜欢
  • 1970-01-01
  • 2021-12-19
  • 2019-09-30
  • 2022-01-21
  • 1970-01-01
  • 2020-10-30
  • 1970-01-01
  • 2019-01-08
  • 1970-01-01
相关资源
最近更新 更多