如何检查Selenium中是否存在webelement?

时间:2019-06-12 15:23:44

标签: java selenium

我想创建一个Java方法,该方法可以检查是否存在实际的硒Web元素。

重要的是,我需要创建一个方法,该方法将获取Webelement作为参数,而不是By或String id。而且我想避免尝试捕获解决方案,如果发生NoSuchElementException,该解决方案将返回false。

public boolean isElementExists(WebElement element) {
    //TODO Implement...
}

示例:

foo.html

<!DOCTYPE html>
<html>
<body>

<button id="button1" type="button">First button</button>

</body>
</html>

FooPage.java

public class FooPage {

    @FindBy(how = How.ID, using = "button1")
    public WebElement fistButton;

    //Missing button
    @FindBy(how = How.ID, using = "button2")
    public WebElement secondButton;

}

FooPageTest.java

public class FooPageTest {
    public void test(FooPage page) {
        page.firstButton.click(); // OK
        page.secondButton.click(); // NoSuchElementException
        //So I need to check if element exists in this class.
        //I can access here to the FooPage, the webelement to check, and to the driver.
    }
}

1 个答案:

答案 0 :(得分:2)

由于Selenium尝试单击第二个按钮时会引发NoSuchElementException,因此请在页面对象中创建一个执行单击的方法:

public class FooPage {
    @FindBy(how = How.ID, using = "button1")
    public WebElement firstButton;

    //Missing button
    @FindBy(how = How.ID, using = "button2")
    public WebElement secondButton;

    public FooPage(WebDriver driver) {
        PageFactory.initElements(driver, this);
    }

    public void clickThebuttons() {
        firstButton.click();

        try {
            secondButton.click();
        } catch (NoSuchElementException ex) {
            // Do something when the second button does not exist
        }
    }
}