Java 构造“try/catch”不捕获异常“NoTouchElementException”

Java 构造“try/catch”不捕获异常“NoTouchElementException”,java,selenium,selenium-webdriver,automated-tests,qa,Java,Selenium,Selenium Webdriver,Automated Tests,Qa,我对SELENIUM是新手,所以如果这个问题听起来很愚蠢,请省省时间。 我写了一个测试,打开页面并检查页面上是否存在一些元素。 当元素不存在时,try/catch截获错误消息并打印到控制台通知。虽然我有积极的结果元素存在cod到试块工作良好。但若我的结果是否定的,元素并没有发现构造捕获不起作用。请解释一下为什么 package ua.com.local; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElemen

我对SELENIUM是新手,所以如果这个问题听起来很愚蠢,请省省时间。 我写了一个测试,打开页面并检查页面上是否存在一些元素。 当元素不存在时,try/catch截获错误消息并打印到控制台通知。虽然我有积极的结果元素存在cod到试块工作良好。但若我的结果是否定的,元素并没有发现构造捕获不起作用。请解释一下为什么

package ua.com.local;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.annotations.Test;

public void OpenPage() {
    driver.findElement(By.xpath("//button[@class='filter-submit__btn']")).click();
            Assert.assertTrue(isElementPresent(driver.findElement(By.xpath("//form[@class='section-filter__form']"))));
            driver.quit();
        }

    public boolean isElementPresent(WebElement element) {
        try {
            element.isEnabled();
            System.out.println("Element found!!! " + element);
            return true;
        } catch (org.openqa.selenium.NoSuchElementException e)  {
            System.out.println("NoSuchElementException!!");
            return false;
        }
    }
控制台输出


原因是,这条线

driver.findElement(By.xpath("//form[@class='section-filter__form']"));
抛出异常的对象不在try块中

你可以这样检查

Assert.assertTrue(isElementPresent(By.xpath("//form[@class='section-filter__form']"));

如果您阅读堆栈跟踪,将发现异常发生在“driver.findElement…”中Alexey R.,你所说的标识符是什么意思?不在try内。@Andrew不是传递webelement的对象,而是传递其对象,该对象是findElement方法的输入,用于查找新的webelement。这样,您就可以在方法内部创建新的webelement。
public boolean isElementPresent(By identifier) {
    try {
        element = driver.findElement(identifier);
    } catch (org.openqa.selenium.NoSuchElementException e)  {
        System.out.println("NoSuchElementException!!");
        return false;
    }

    element.isEnabled();
    System.out.println("Element found!!! " + element);
    return true;
}
Assert.assertTrue(isElementPresent(By.xpath("//form[@class='section-filter__form']"));