简体   繁体   中英

Catch method taking long time to execute

In selenium automation i'm checking for element displaying status by using below code

public boolean isDisplayed(String xpath){
try{
return driver.findElement(By.xpath(xpath)).isDisplayed();
}catch (Exception e){
return false;
}

}

but the issue is, if the element is not displaying it will go to catch statement and it takes more time to execute catch statement. How to make it fast this. Could you please help me here. Thanks in advance

At first, try to wait for the availability of element using explicit wait and then check isDisplayed attribute: the reason for waiting is implicit waiting for element because when the element is not interactable it waits to element or waiting time is reached.

WebDriverWait wait = new WebDriverWait(WebDriver, timeSpan);            wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.xpath(xpath)));
try{
return driver.findElement(By.xpath(xpath)).isDisplayed();
}
catch (Exception e){
return false;
}

Try use .findElements , it will return number of the elements.

public boolean isDisplayed(String xpath){
    if(driver.findElements(By.xpath(xpath)).size()>0) {
        return driver.findElement(By.xpath(xpath)).isDisplayed();
    }else {
        return false;
    }
}

If size>0 it will return first element is display.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM