Selenium locator extension

In Selenium, there are multiple locator functions, such as

  • By.CssSelector
  • By.XPath
  • By.Id
  • By.Name
  • ……

In my case, I would like to use different format, which I can call one method instead of so many, it would be easier to store the locator information somewhere else. The locator format would be ByMethod = selector to Find, for example:

css=input[value=’clear’][type=button]

So an extension method was created for this, here is the code snippet.

public static ReadOnlyCollection<IWebElement> FindElements(this ISearchContext context, string properties)
{

    ReadOnlyCollection<IWebElement> controls = null;

    var by = GetByFromProperty(properties);

    if (by != null)
    {
        controls = context.FindElements(by);
    }

    return controls;
}

public static By GetByFromProperty(string propToFind)
{
    var pos = propToFind.IndexOf('=');
    var locHow = propToFind.Substring(0, pos).Trim();
    var locUsing = propToFind.Substring(pos + 1).Trim();

    if (locHow.ToUpper().StartsWith("CSS"))
    {
        locHow = "CssSelector";
    }
    
    return (By)GetByMethod(locHow).Invoke(null, new[] { locUsing });

}

public static MethodInfo GetByMethod(string methodName)
{
    var methods = (typeof(By)).GetMethods();
    foreach (var m in methods)
    {
        if (m.Name.ToUpper() == methodName.ToUpper())
        {
            return m;
        }
    }

    throw new MissingMethodException("Method not exist in By Class: " + methodName);
}