[英]How can I check if webelement exists in Selenium?
I want to create a java method which can check if an actual selenium webelement exists. 我想创建一个Java方法,可以检查是否存在实际的硒Webelement。
It's important, that I need to create a method, which would get a Webelement as a parameter, not a By or String id. 重要的是,我需要创建一个方法,该方法将获取Webelement作为参数,而不是By或String id。 And I want to avoid try-catch solution, which would return a false if a NoSuchElementException would occure.
而且我想避免尝试捕获解决方案,如果发生NoSuchElementException,该解决方案将返回false。
public boolean isElementExists(WebElement element) {
//TODO Implement...
}
Example: 例:
foo.html foo.html
<!DOCTYPE html>
<html>
<body>
<button id="button1" type="button">First button</button>
</body>
</html>
FooPage.java 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 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.
}
}
Since Selenium throws a NoSuchElementException when attempting to click on the second button, create a method in your page object that does the clicking: 由于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
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.