2014-01-24 49 views
10

我想为Selenium编写我自己的ExpectedConditions,但我不知道如何添加一个新的。有没有人有一个例子?我无法在网上找到任何教程。如何为Selenium添加自定义ExpectedConditions?

在我目前的情况下,我想等到一个元素存在,是可见的,启用AND没有attr“aria-disabled”。我知道这个代码不起作用:

var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(seconds)); 
return wait.Until<IWebElement>((d) => 
    { 
     return ExpectedConditions.ElementExists(locator) 
     && ExpectedConditions.ElementIsVisible 
     && d.FindElement(locator).Enabled 
     && !d.FindElement(locator).GetAttribute("aria-disabled") 
    } 

编辑:一点附加信息:我遇到的问题是与jQuery选项卡。我在禁用的选项卡上有一个表单,它将在标签变为活动状态之前开始填写该选项卡上的字段。

回答

27

“期望的状态”只不过是一个更使用lambda表达式的匿名方法。从.NET 3.0开始,这些已成为.NET开发的主要工具,特别是随着LINQ的发布。由于绝大多数.NET开发人员都习惯于使用C#lambda语法,因此WebDriver .NET绑定'ExpectedConditions实现只有几个方法。

创建等待像你问的会是这个样子:

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); 
wait.Until<IWebElement>((d) => 
{ 
    IWebElement element = d.FindElement(By.Id("myid")); 
    if (element.Displayed && 
     element.Enabled && 
     element.GetAttribute("aria-disabled") == null) 
    { 
     return element; 
    } 

    return null; 
}); 

如果你不使用这个结构经历,我会建议变得如此。它只可能在未来的.NET版本中变得更加流行。

+0

不应该? – chill182

+0

当然。编辑纠正。感谢您指出。 – JimEvans

+1

由于这个答案已经在IRC中连接了好几次,我还会指出它应该使用d.FindElement,因为这是驱动程序的lambda变量 –

2

我理解ExpectedConditions(我认为)背后的理论,但我经常发现它们在实践中很麻烦并且很难使用。

我会去用这种方法:

public void WaitForElementPresentAndEnabled(By locator, int secondsToWait = 30) 
{ 
    new WebDriverWait(driver, new TimeSpan(0, 0, secondsToWait)) 
     .Until(d => d.FindElement(locator).Enabled 
      && d.FindElement(locator).Displayed 
      && d.FindElement(locator).GetAttribute("aria-disabled") == null 
    ); 
} 

我会很乐意从一个答案,学习使用所有ExpectedConditions在这里:)

+0

因此通过这种方式,在需要的地方,我们可以调用这个方法?因为在其他方法中,我们必须将其作为所有需要的地方的表达。纠正我,如果我错了。 – user1925406

+0

这是正确的@ user1925406 –

0

我已将WebDriverWait和ExpectedCondition/s的示例从Java转换为C#。

Java版本:

WebElement table = (new WebDriverWait(driver, 20)) 
.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("table#tabletable"))); 

C#版本:

IWebElement table = new WebDriverWait(driver, TimeSpan.FromMilliseconds(20000)) 
.Until(ExpectedConditions.ElementExists(By.CssSelector("table#tabletable")));