我们可以在同一个程序中有两个显式等待

时间:2013-06-05 20:12:23

标签: c# selenium selenium-webdriver nosuchelementexception

我在同一个程序中有两个明确的等待。一个用于WaitForElement和一个WaitForPageLoad.But它似乎不起作用。当我将其中一个更改为隐式等待时,它可以正常工作。否则代码会在开始时失败。在selenium中开始,所以不知道为什么它会失败。

错误:

 NoSuchElementException

等待:已经在两种不同的方法中使用了这些

  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;
    }

程序在程序中使用的代码

   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);

1 个答案:

答案 0 :(得分:1)

我认为等待元素的更通用方法对您的用途更好。因此,请使用通用表达式并传入搜索条件。例如:

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)));
}

如果等待超时,这将抛出异常,因此您还可以添加try / catch以不同方式报告失败。我个人在我的测试解决方案中使用它,在一个开关中,每个常用的搜索类型都有一个案例。然后我传入搜索类型搜索字词(例如,elementAttribute ID,字符串myTextboxID)。

话虽如此,我看不出任何明显错误的代码会导致它无法正常工作。

相关问题