0

I am using headless mode with ChromeDriver. I find an element by calling

 var name= Driver.FindElement(By.Id("TestLabelName"));
 if (name== null)
 { 
 }

The issue here is that if the element is not present it just exceptions and stops and doesnt do the null check. Is there a way to return either the element or just null ? Or return the console window data without having to wrap every FindElement around a try catch ?

Kristy
  • 39
  • 5

1 Answers1

0

Use FindElements instead of FindElement.

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

Text copied from: Test if element is present using Selenium WebDriver?


Also you can write a static method that looks for an element:

    public static IWebElement _FindElement(ChromeDriver inCromeDriver, string inNameElementId)
    {
        try
        {
            var name = inCromeDriver.FindElement(By.Id(inNameElementId));
            return name;
        }
        catch (System.Exception ex)
        {
            System.Console.WriteLine(ex);
            return null;
        }
    }
BouRHooD
  • 200
  • 1
  • 14
  • is there anything similar to Assert.Equal as used in ui tests ? – Kristy Oct 07 '22 at 05:04
  • @Kristy Yes, you can write a static method that looks for an element, if an exception occurs in this method, then return null – BouRHooD Oct 07 '22 at 05:13
  • great thanks.. So i assume if an exception is raised , I can just call Driver.close() to quit the console ? And log errors to a log file ? Is that best practice ? – Kristy Oct 07 '22 at 06:16