[英]How can I check if webelement exists in Selenium?
我想創建一個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.
}
}
由於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.