【问题标题】:NoSuchElementException not caught [closed]NoSuchElementException 未捕获 [关闭]
【发布时间】:2022-01-11 01:56:31
【问题描述】:

我正在调试 Java Selenium 中的测试,并创建了一个 try and catch 来捕获 NoSuchElementException 错误。在评估表达式中,我看到这确实是错误,但实际上软件继续“最终”并且不执行“尝试”而不是“捕获”中所写的内容。 你知道为什么吗?

try {
        WebElement cell = table.findElement(By.xpath("//table/tbody/tr/td["+returnColumnText+"]"));
        exeptedText = cell.getText();
    }
    catch (NoSuchElementException e){
        System.out.println("You are trying to access a non-existent cell. Check the values you entered.");
    }

【问题讨论】:

  • 请发布完整的、可重现的代码。此外,在这种情况下,如果页面是公共的,则需要完整的错误描述(包括堆栈跟踪,如果可用)以及页面 URL。如果没有,DOM 的提取可能就足够了。发生这种情况的原因可能有很多,包括 Web 元素确实存在。我们无法判断,因为我们无权访问任何此类信息。
  • 确保您已导入 org.openqa.selenium.NoSuchElementException 而不是 java.util.NoSuchElementException
  • @GurmanjotSingh 我确信情况并非如此。否则,OP 会抱怨代码无法编译。在这种情况下,OP 暗示代码运行并跳过 catch 块。
  • exeptedText = cell.getText(); 处设置断点,调试代码并检查cell 属性。您可能会发现该元素的位置为 0,0 或属性为 hidden=true 或类似的东西。考虑甚至可能有更多cell 元素位于同一定位器中。

标签: java selenium exception intellij-idea automation


【解决方案1】:

您要捕获的异常的全名是 org.openqa.selenium.NoSuchElementException。然而,Java 会尝试捕获 java.util.NoSuchElementException 作为默认值。

是的,您应该将异常的全名声明为如下 sn-p。

try {
        WebElement cell = table.findElement(By.xpath("//table/tbody/tr/td["+returnColumnText+"]"));
        exeptedText = cell.getText();
    }
    catch (org.openqa.selenium.NoSuchElementException e){
        System.out.println("You are trying to access a non-existent cell. Check the values you entered.");
    }

【讨论】:

  • 谢谢!我更改了异常的全名,异常被捕获。
猜你喜欢
  • 1970-01-01
  • 2018-04-07
  • 2019-03-02
  • 2023-03-15
  • 2013-06-20
  • 2023-03-12
  • 1970-01-01
  • 2014-08-04
  • 1970-01-01
相关资源
最近更新 更多