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

pityo10000:

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

重要的是,我需要创建一个方法,该方法将获取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.
    }
}
格雷格·伯格哈特(Greg Burghardt):

由于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
        }
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章