Skip to content

Instantly share code, notes, and snippets.

@bangonkali
Created May 14, 2015 05:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bangonkali/9720359c60c76f99b163 to your computer and use it in GitHub Desktop.
Save bangonkali/9720359c60c76f99b163 to your computer and use it in GitHub Desktop.
Selenium to check if element exist.
public IWebElement GetIfExists(By element, double timeout = 30000, int delay = 1500)
{
DateTime startDateTime = DateTime.Now;
while ((DateTime.Now - startDateTime).TotalMilliseconds < timeout)
{
try
{
WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromMilliseconds(timeout));
IWebElement myDynamicElement = wait.Until(d =>
{
if (d == null) throw new ArgumentNullException("d");
try
{
var returnElement = d.FindElement(element);
Thread.Sleep(delay);
if (returnElement.Enabled && returnElement.Displayed)
return returnElement;
return null;
}
catch (Exception ex)
{
Debug.WriteLine("Exception: " + ex.Message);
return null;
}
});
return myDynamicElement;
}
catch (Exception exception)
{
Debug.WriteLine("Exception: " + exception.Message);
// Ignore error.
}
}
return null; // Never result to something.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment