StaleElementReferenceException:陈旧元素引用:

时间:2014-10-08 19:02:44

标签: java selenium xpath selenium-webdriver

我需要从代码中访问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的情况下打印String s1和s2的值。 我可以访问“Enterprise”文件夹但无法访问“Enter”folderId。 由于'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 Developer Tools选择Enter folderId,如下所示:

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

日食中的实际输出: 线程“main”中的异常org.openqa.selenium.StaleElementReferenceException:陈旧元素引用:元素未附加到页面文档   (会议信息:chrome = 37.0.2062.124)

1 个答案:

答案 0 :(得分:2)

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...