我正面临Stale Element Exception的问题。我已经用Google搜索并在stackoverflow中找到了一些答案,但都没有奏效。我发现当DOM元素被销毁并再次创建时会发生此异常。在这里,我的场景是我有一个包含记录的表格,下面有一个文本,"显示6行中的1到6行"。当我点击刷新按钮时,会发生此异常。
String recordsBeforeRefresh = getRecordsCountFromTable(waitForElement(By.xpath(properties.getProperty("RefreshPage.Icon"))).getText());
clickElement(By.xpath(properties.getProperty("RefreshPage.Button")), "Refresh");
String recordsAfterRefresh = getRecordsCountFromTable(waitForElement(By.xpath(properties.getProperty("RefreshPage.Icon"))).getText());
if(recordsBeforeRefresh.equals(recordsAfterRefresh))
{
return true;
}
else
{
return false;
}
waitforElement在另一个类
中protected WebElement waitForElement(final By fieldLocator) {
return waitForElement(fieldLocator, 30);
}
protected WebElement waitForElement(final By fieldLocator, int timeoutSeconds) {
Wait<WebDriver> wait = new FluentWait<WebDriver>(getDriver()).withTimeout(timeoutSeconds, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS).ignoring(NoSuchElementException.class);
WebElement field = null;
try {
field = wait.until(new Function<WebDriver, WebElement>() {
@Override
public WebElement apply(WebDriver driver) {
return driver.findElement(fieldLocator);
}
});
} catch (Throwable t) {
throw new AutomationError(t);
}
return field;
}
getRecordsCountFromTable(String)具有正则表达式模式匹配方法,用于获取记录总数。
请帮忙......
堆栈追踪:
stale element reference: element is not attached to the page document
(Session info: chrome=47.0.2526.106)
(Driver info: chromedriver=2.20.353145 (343b531d31eeb933ec778dbcf7081628a1396067),platform=Windows NT 6.3 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 137 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '2.48.2', revision: '41bccdd10cf2c0560f637404c2d96164b67d9d67', time: '2015-10-09 13:08:06'
System info: host: '7YYCXY1', ip: '10.101.121.23', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_25'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, chrome={userDataDir=C:\Users\LSANAP~1\AppData\Local\Temp\scoped_dir6484_22708}, takesHeapSnapshot=true, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=47.0.2526.106, platform=WIN8_1, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: dd9a7e9b7d9d0f51a61f8075ed7bd843
错误发生在String afterrefresh line ...
之后答案 0 :(得分:3)
@Lokesh S,您可以尝试以下步骤,最有可能使其发挥作用:
步骤1:点击刷新或执行操作
步骤2:等待元素显示使用元素的显式等待
第3步:再次执行一个抛出StaleElementException的findElement。