0

If any element doesnot exists in Selenium Testing, then I am unable to handle it. I have tried this code.

    public static bool IsElementPresent(IWebDriver driver, By by)
    {
        try
        {
            driver.FindElement(by);
            return true;
        }
        catch (NoSuchElementException)
        {
            return false;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

It shows timeout exception takes too much time more than 1 min and finally handled by main Exception class, but my automation testing stops, And I dont want to stop my testing.

I have tried this code snippet also.

public bool IsElementPresent(IWebDriver driver, By by, TimeSpan? timeSpan)
{
    bool isElementPresent = false;
    try
    {
        if (timeSpan == null)
        {                    
            timeSpan = TimeSpan.FromMilliseconds(2000);
        }
        var driverWait = new WebDriverWait(driver, (TimeSpan)timeSpan);                       
        driverWait.IgnoreExceptionTypes(typeof(WebDriverTimeoutException));
        isElementPresent=driverWait.Until(x => x.FindElements(by).Any());
        return isElementPresent;
    }
    catch (NoSuchElementException nex) 
    {
        return false;
    }
    catch (Exception ex) 
    {
        return false;
    }
}

What should I do so that in small span of time it returns true or false.

Eugene
  • 1,865
  • 3
  • 21
  • 24

3 Answers3

1

Another option would be something like

return driver.FindElements(by).length > 0;
Sebastian
  • 5,721
  • 3
  • 43
  • 69
0

I generally use the Displayed property. I use the page object model with pre-determined IWebElements in the example below:

    public bool IsPageObjectPresent(IWebElement PageObject)
    {
        try
        {
            if (PageObject.Displayed)
            {
                Console.WriteLine("Element is displayed");
                return true;
            }
            else
            {
                Console.WriteLine("Element present but not visible");
                return true;
            }
        }
        catch (NoSuchElementException)
        {
            Console.WriteLine("Element not present");
            return false;
        }
        catch (StaleElementReferenceException)
        {
            Console.WriteLine("Stale element present");
            return false;
        }
    }
CynicalBiker
  • 579
  • 5
  • 14
  • Its also not working, when element is not present, Time Out Exception, I want to check for element present or not present with maximum of 10 sec timespan. – Sanjeev Agrawal Oct 21 '15 at 07:45
-1
     try{

        // Add your complete portion of code here //

        System.out.println("Portion of code executed Successfully");
        }
        catch(Exception name)
        {
        System.out.println("Portion of code failed");   
        }

Please try and let me know.......

Ninja java
  • 105
  • 9