2014-01-24 91 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")));