What is the best approach for Timeout using Selenium using Webdriver
c#, selenium, selenium-webdriver, webdriver
Solution
Thread.Sleep() is a very discouraged way to implement your waits
This code is outlined on the selenium documentation http://seleniumhq.org/docs/04_webdriver_advanced.html
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement category = wait.Until<IWebElement>((d) =>
{
return d.FindElement(By.Id("ctl00_ContentPlaceHolder1_Filter"));
});
That is an example of an explicit wait where selenium will not execute any actions until your element is found
An example of an implicit wait is:
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
IWebElement category = driver.FindElement(By.Id("ctl00_ContentPlaceHolder1_Filter"));
In implicit waits the driver will wait for a given amount of time and poll the DOM for any elements that do not exist.
EDIT
public WaitForElement(string el_id)
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement category = wait.Until<IWebElement>((d) =>
{
return d.FindElement(By.Id(el_id));
});
}
Problem
I have run into a problem. My web page has a `DropDownList` control. Once the `DropDownList` value changes (by selecting a different value), the page refreshes and it renders the contents. And then I have to use `Thread.Sleep(2000);` before it goes and `FindElement`. My question: What is the best way to wait till the page loads? I have so many instances of `Thread.Sleep(2000)` in my code that I am beginning to think this is not the best way to approach the problem. Here is my code: ``` [TestInitialize()] public void Setup() { if (BaseIntegrationTest.browserType.Equals(BaseIntegrationTest.IE)) { driver = new InternetExplorerDriver(); } else if (BaseIntegrationTest.browserType.Equals(BaseIntegrationTest.CHROME)) { //driver = new ChromeDriver(); } else if (BaseIntegrationTest.browserType.Equals(BaseIntegrationTest.FIREFOX)) { driver = new FirefoxDriver(); } } ``` And the second part: ``` [TestMethod] public void testVerifyData() { // ................... // ................... driver.FindElement(By.XPath("//*[@id='ctl00_NavigationControl1_lnke']")).Click(); Thread.Sleep(2000); //select from the dropdownlist. IWebElement catagory = driver.FindElement(By.Id("ctl00_ContentPlaceHolder1_Filter")); SelectElement selectCatagory = new SelectElement(catagory); selectCatagory.SelectByText("Employee"); Thread.Sleep(2000); // ................... // ................... } ```