How to continue script when element is not found in selenium

  • I am using selenium web driver and appium as this is mobile application automation,

    I am trying to check that if element is there or not and based on that I have put conditions.

     long starttime = System.currentTimeMillis();
     long endtime = starttime + 60*1000; // 60 seconds * 1000 ms/sec;
    while(System.currentTimeMillis() < endtime)
        notcount = driver.findElement(;
        System.out.println("No Element found");

    Here issue is when element is not there , instead to redirect to ELSE part , selenium stops execution and throwing exception.

    I do not want to use List -findelements here as that is taking long time to find element.

    I googled for "selenium wait and if not found do something" first two hits had the solution :) See my answer.

  • Use findElements instead of findElement.

    findElements will return an empty list if no matching elements are found instead of an exception.

    To check that an element is present, you could try this

    Boolean isPresent = driver.findElements(By.yourLocator).size() > 0

    This will return true if at least one element is found and false if it does not exist.

    Text copied from:

    Another posbility is to use a Try/Catch construction, see this for more info:

    Yes I agree and already tried this solution but it takes long time to search element even if element is not there and that's why I have mentioned that I do not want to use `LIST or findelements ` for this.

    Use the try/catch construction instead then. But how much longer does it really take? Wouldn't except to much, unless your finding hundreds of elements. Also I wonder if your really want to continue the test if an element cannot be found, why are you looking for it then? Let the test fail.

    I am also surprised that I am finding only 1 element and for that only webdriver is taking long time. I want test continue in manner like if element not found then go to ELSE part..

    Having if/then/else constructs in the test is an anti-pattern to me. The test should describe one execution path and avoid any logic. If something blocks this execution path, then fail fast, as suggested. If you want to cover multiple execution paths then create multiple tests where each covers one execution path.

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM