The approach below extends FindElement and shows how to locate the target element using multiple probable locators without using XPath.
public static IWebElement FindElementEx(this IWebDriver driver, params By[] by)
{
string ex = "";
foreach (By _by in by)
{
try
{
return driver.FindElement(_by);
}
catch (NoSuchElementException)
{
ex += "Unable to find element with " + _by.ToString() + "\n";
}
}
throw new NoSuchElementException(ex);
}
// usage
driver.FindElementEx(By.Id("userName"), By.Name("userName")).SendKeys("element found"); |
public static bool IsElementPresent(this IWebDriver driver, params By[] by)
{
try
{
driver.FindElementEx(by);
return true;
}
catch (NoSuchElementException) { return false; }
}
// usage
driver.IsElementPresent(By.Id("userName"), By.Name("userName")).ToString(); |
Below is what I was using earlier, but I find the inclusion of new FindElementEx
method (previous section) much more suitable for my needs.
public delegate IWebElement FindElement();
public static bool IsElementPresent(FindElement findElement)
{
try
{
findElement();
return true;
}
catch { return false; }
}
// usage
IsElementPresent(() => driver.FindElement(By.Name("userName"))); |