首页 > 解决方案 > 无法捕获 Selenium NoSuchElementError (Javascript)

问题描述

编辑:不知道为什么这被标记为已回答,因为链接的问题都没有处理这个问题,也没有使用 Javascript。我正在寻找一种方法来捕捉这个错误,而不是阻止它,因为像 invisibilityOfElementLocated 这样的方法在 Javascript 版本中不可用。

我有一个网站,我正在设置一些关于使用 nodeJS、selenium 和 mocha 的基本自动化测试。首次打开站点时,用户单击一个框并关闭欢迎消息(此处为“elemId”),然后不再在 DOM 中呈现。在开始实际测试之前,我需要检查它是否不再存在,但尽管使用了 stalenessOf,但我经常收到 NoSuchElementError 的硒错误。如果我可以捕获并忽略此异常,这将不是问题,但不幸的是,捕获它似乎不起作用。以下是有问题的代码和我收到的错误消息。

    // Check it no longer exists before moving on

    driver.wait(until.stalenessOf(driver.findElement(By.id('elemId'))))

    .then(null, function(err) {

        // Sometimes this throws an error even though the element is stale

        // Using this syntax should catch the error, as it is a selenium error, not a javascript error

        console.log('Threw error but that is acceptable');

    })

NoSuchElementError:没有这样的元素:无法找到元素:{“方法”:“css选择器”,“选择器”:“* [id =“elemId”]“}

标签: javascriptseleniummocha.js

解决方案


异常发生在调用 stalenessOf 之前。
编码

driver.findElement(By.id('elemId')

将生成异常 NoSuchElementFound。

方法 stalenessOf:
方法 stalenessOf 没有做你认为它做的事情。该方法期望元素存在并且将等待直到引发 StaleElementException。这意味着该元素存在,但随后会被刷新或从 DOM 中删除。

尝试使用方法 invisibilityOfElementLocated:

 wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("elemId"));

对于以下任一条件,该方法将返回 True:

  1. 元素从未附加到 DOM
  2. 一旦元素在您设定的时间内不存在于 DOM 上。如果仍然存在,它将引发TimeOutException.

推荐阅读