Question

I have two explicit waits in the same program. One for WaitForElement and one WaitForPageLoad.But it doesn't seem to work. When i change one of them to implicit wait, it works fine. Otherwise the code fails at the begining itself.Beginner in selenium so no idea why it failed.

Error:

 NoSuchElementException

waits:have used these in two different methods

  WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(3));
    {
       IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
       {
          return d.FindElement(By.ClassName("header"));
       });
       if (myDynamicElement != null) return true;
    }

  WebDriverWait _wait = new WebDriverWait(driver, TimeSpan.FromSeconds(3));
    {
       IWebElement _myDynamicElement = _wait.Until<IWebElement>((d) =>
       {
          return d.FindElement(By.ClassName("header-buttons"));
       });
       if (_myDynamicElement != null) return true;
    }

code where the method is used in the program

   WaitForElementPresent(By.CssSelector("div[class='tagged-text search-text']>input"));
 //Enter the item to search
   driver.FindElement(By.CssSelector("div[class='tagged-text search-text']>input")).Clear();
   driver.FindElement(By.CssSelector("div[class='tagged-text search-text']>input")).SendKeys(searchItem + Keys.Enter);
Was it helpful?

Solution

I think a more generic approach to waiting for an element would be better for your uses. So instead use a generic expression and pass in your search criteria. For example:

public void WaitForElementById(string elementId, int timeout = 5)
{
    //Where '_driver' is the instance of your WebDriver
    WebDriverWait _wait = new WebDriverWait(_driver, new TimeSpan(0, 0, timeout));
    IWebElement element = _wait.Until(x => x.FindElement(By.Id(elementId)));
}

This will throw an exception if the wait times out so you could also adding in a try/catch to report failings differently. I personally use this in my testing solution within a switch that has a case for each of my commonly used search types. I then pass in the search type and the search term (eg, elementAttribute ID, string myTextboxID).

With that said, I can't see anything obviously wrong with your code that would cause it not to work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top