Wednesday 14 March 2018

How to Check Element Present on Page With Selenium Wrapper Automation

When you are are performing any operation on UI element then first you have to check weather element is present on page or not. If element is not present on page then your code will throw exception.

So, every time you have to check first weather element is present or not. If element is present then go ahead otherwise don't go ahead.

If you use isDisplayed() function for checking element then if element is not present then it will throw exception. So, you have to write that element operation in try/catch block. Same for all element operations. This is not good approach when you are working on selenium automation framework.

You have to use selenium wrapper automation for handling element check.

I have create below function for check element is present on page or not.


    public boolean mElementCheck(WebDriver driver, WebElement vElement)
    {
        final int WAIT_TIME = 2; //seconds
        final int RETRIES = 5;

        boolean bElementCheck = true;
                
        // The max wait time is 10 seconds(2 seconds with 5 retries)
        
        WebDriverWait wait = new WebDriverWait(driver, WAIT_TIME);
        int retries = 0;
        while (true)
        {
            try
            {
             wait.until(ExpectedConditions.visibilityOf(vElement));             
             bElementCheck = true;
             return bElementCheck;
            }
            catch (Exception e)
            {
             if (retries < RETRIES)
                {                 
                    retries++;
                    continue;
                }
                else
                {
                 System.out.println("WebElement not found.");                 
                 bElementCheck = false;
                 return bElementCheck;
                }
            }
        }
                        
    }

Function is returned Boolean value True/False. If element is present then True otherwise False.

I have used Explicit wait in function for handle wait while checking element present or not.

For more information regarding Wait handling in selenium then please go to below link.
Implicit Wait Vs. Explicit Wait Vs. Fluent Wait

Now, you can use this function easily with IF statement and it will not throw any exception if element is not present.

Please add comment is you have any question.

Popular