【发布时间】:2015-09-29 09:03:56
【问题描述】:
我正在运行 node.js 和 Selenium WebDriverJS。我的一项测试因以下错误而失败:
UnknownError: unknown error: Runtime.evaluate threw exception: Error: element is not attached to the page document
我知道这本质上是一个 StaleElementReferenceException,但我还没有找到可靠的解决方法。我尝试了以下方法但没有成功:
-
等待该元素出现在页面上,然后再查找并点击该元素
waitForElement: function (selector, timeout) { if (typeof(timeout) === 'undefined') { timeout = 3000; } driver.wait(function() { return driver.findElements(selector).then(function(list) { return list.length > 0; }); }, timeout); } - 在找到并点击元素之前等待一段明确的时间 (
driver.sleep(1000)) - 在点击元素之前多次查找元素(使用
.findElement()) -
使用承诺链来捕获任何错误并尝试重新单击元素
driver.getTitle().then(function(title) { driver.findElement(webdriver.By.xpath(...)).click(); }).thenCatch(function(e) { driver.findElement(webdriver.By.xpath(...)).click(); }); -
使用带有递归函数的承诺链来不断尝试重新点击元素
var getStaleElement = function(selector, callback) { var element = driver.findElement(selector); callback(element); }).thenCatch(function(e) { getStaleElement(selector, callback); }); var clickSelf = function(ele) { return ele.click() }; driver.getTitle().then(function(title) { driver.findElement(webdriver.By.xpath(...)).click(); }).thenCatch(function(e) { getStaleElement(webdriver.By.xpath(...), clickSelf); }); - 方法 4 和 5 使用
.then()的 errback 参数代替.thenCatch() - 以上组合
Selenium 似乎无法捕获此特定错误。我使用 print 语句来确认 NoSuchElementError 等其他错误被 .thenCatch() 捕获。是否有一种解决方法可以让我处理陈旧的元素?
【问题讨论】:
-
我忘了在原帖中提到这个错误不是每次运行测试都会出现,而是偶尔出现。
-
你有没有找到解决这个问题的方法?
标签: javascript selenium selenium-webdriver webdriver