function to check whether an element is present in

2019-07-29 08:42发布

问题:

Created a function to check whether an element is present on a page or not. Intention is to wait for a specified period of time and then return false, if not present.

public boolean isElementPresent(final WebElement element) {

    Wait<WebDriver> wait = new WebDriverWait(driver, 60);
    return wait.until(new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver webDriver) {
            return element.isDisplayed() != false;
        }
    });
}

But this is throwing exception in case of element not found

回答1:

It is throwing exception because findElement will throw exception if no element is found. It is used in isDisplayed() method. You can 1st check, whether element is present on page then check whether it is displayed. Use following to make 1st check.

driver.findElements(byLocator).size>0


回答2:

The following is a crude solution. But it works nevertheless :p

public boolean isElementPresent() {
    try {
        new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocatedBy(By.id(""));
        return true;  
    } catch (TimeOutException e) {
        return false;
    }
}

When we use the WebDriverWait Class for waiting for a element to be present in the web page, a TimeOut Exception is thrown after the specified time. We catch it and return false. If no exception is thrown(if element is found), we return true.

If you are looking for checking whether the element is enabled or is displayed, explore the isDisplayed or isEnabled methods associated with WebElement. But please note that if the element is not physically present in the webpage, an exception is thrown.



回答3:

Here is another less 'barbaric' method :-

public boolean isElementPresent() {  
    List<WebElement> elements = new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementsLocatedBy(By.id(""));
    if (elements.isEmpty()) {
        return false;
    } else {
        return true;
    }
}


回答4:

This will help you.

 public boolean fncCheckElement() {
try {
    WebElement element = (new WebDriverWait(driver,1)).until(ExpectedConditions.presenceOfElementLocated((By.id("ID"))));
 system.out.println("Element is present in web page")  
 return true;  
} catch (Throwable e) {
    ex.printStackTrace();
    system.out.println("Element is not present  in web page")
    return false;
}}

Enjoy!