简体   繁体   中英

How can i set an error in output when calling FindElement in chromedriver headless mode?

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?

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;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM