Search code examples
javaseleniumselenium-webdriverexceptionnosuchelementexception

Fastest way to kill NoSuchElementException or any Exception when element is not found in Selenium WebDriver


Is there a fastest way to kill the process in catch (when using try/catch)? Cos usually it takes 1 minute to make the process proceed after exception has been caught.

I have this code below:

public boolean elementExist(WebDriver driver, By locator){
    boolean exist = false;
    try{
        exist = driver.findElements(locator).size()>0;

    } catch (org.openqa.selenium.NoSuchElementException e) {
        return false;
    }

    return exist;
}

Whenever the script didn't found the element it waits 1 minute to proceed. I need to lower down the 1 minute to at least 5-10 secs bcos it's such a waste of time.

Or if there's another way and faster to handle if the element does not exist please help.


Solution

  • Try to set

    driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
    

    Right after

    WebDriver driver = new FirefoxDriver(); //or ChromeDriver 
    

    ImplicityWait basically tells Selenium "Hey, every operation you are trying to perform should Timeout after 3 seconds"