I have the following code for selecting an option from given list and it usually works, but sometimes it fails with NoSuchElement exception on the second if. I was under the
Instead of having to try catch every instance, why not create a helper/extension method to take care of that for you. Here it returns the element or returns null if it doesn't exist. Then you can simply use another extension method for .exists().
IWebElement element = driver.FindElmentSafe(By.Id("the id"));
///
/// Same as FindElement only returns null when not found instead of an exception.
///
/// current browser instance
/// The search string for finding element
/// Returns element or null if not found
public static IWebElement FindElementSafe(this IWebDriver driver, By by)
{
try
{
return driver.FindElement(by);
}
catch (NoSuchElementException)
{
return null;
}
}
bool exists = element.Exists();
///
/// Requires finding element by FindElementSafe(By).
/// Returns T/F depending on if element is defined or null.
///
/// Current element
/// Returns T/F depending on if element is defined or null.
public static bool Exists(this IWebElement element)
{
if (element == null)
{ return false; }
return true;
}