簡體   English   中英

如何為 Selenium 添加自定義 ExpectedConditions?

[英]How to add custom ExpectedConditions for Selenium?

我正在嘗試為 Selenium 編寫我自己的 ExpectedConditions,但我不知道如何添加一個新的。 有人有例子嗎? 我在網上找不到任何有關此的教程。

在我目前的情況下,我想等到元素存在、可見、啟用並且沒有屬性“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 選項卡。 我在禁用的選項卡上有一個表單,它會在選項卡變為活動狀態之前開始填寫該選項卡上的字段。

“預期條件”只不過是使用 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 的未來版本中變得更加流行。

我理解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的答案中學習:)

由於所有這些答案都指向 OP 使用帶有新等待的單獨方法並封裝函數而不是實際使用自定義預期條件,因此我將發布我的答案:

  1. 創建一個類 CustomExpectedConditions.cs
  2. 將您的每一個條件創建為靜態可訪問方法,您以后可以從等待中調用這些方法
public class CustomExpectedConditions { public static Func<IWebDriver, IWebElement> ElementExistsIsVisibleIsEnabledNoAttribute(By locator) { return (driver) => { IWebElement element = driver.FindElement(locator); if (element.Displayed && element.Enabled && element.GetAttribute("aria-disabled").Equals(null)) { return element; } return null; }; } }

現在您可以像任何其他預期條件一樣調用它,如下所示:

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(TIMEOUT));
wait.Until(CustomExpectedConditions.ElementExistsIsVisibleIsEnabledNoAttribute(By.Id("someId")));

我已將 WebDriverWait 和 ExpectedCondition/s 的示例從 Java 轉換為 C#。

爪哇版:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM