Search Here!

Tuesday, April 24, 2012

Selenium WebDriver: Wait Until Element

How to wait for an element till it comes on the page. C# code to wait for an element in a very generic manner using Selenium WebDriver.

public void WaitUntilElement(By by)
{
Boolean elementFound = false;
Stopwatch sw = new Stopwatch();
sw.Start();
int minutesToWait = Int32.Parse(ConfigurationManager.AppSettings["WaitUntillElementMinutes"]);
while (sw.Elapsed.Minutes < minutesToWait)
{
try
{
var elements = WebDriver.FindElements(by);
if (elements != null && elements.Count > 0)
{
elementFound = true;
break;
}
}
catch (Exception)
{ }
}
if (!elementFound)
{
throw new TimeoutException(string.Format("The expected element '{0}' has not found nder specified time interval of '{1}' minute(s).", by, ConfigurationManager.AppSettings["WaitUntillElementMinutes"]));
}
sw.Stop();
sw = null;
}

1 comment:

  1. Thabk you Manish Baaaji, this help with my work anyways, I sure their should be a way to port this to java
    Manav Brar

    ReplyDelete