5

指定されたリストからオプションを選択するための次のコードがあり、通常は機能しますが、2番目のifでNoSuchElement例外が発生して失敗することがあります。要素が見つからない場合は、ループに戻るだけだという印象を受けました。説明はとても簡単だと思います...誰かが私を教えてくれませんか?

    public static void selectFromList(String vList, String vText, IWebDriver driver)
    {
        for (int sec = 0; ; sec++)
        {
            System.Threading.Thread.Sleep(2500);
            if (sec >= 10) Debug.Fail("timeout : " + vList);
            if (driver.FindElement(By.Id(ConfigurationManager.AppSettings[vList])).Displayed) break;
        }
        new SelectElement(driver.FindElement(By.Id(ConfigurationManager.AppSettings[vList]))).SelectByText(vText);
    }
4

3 に答える 3

6

すべてのインスタンスをキャッチしようとする代わりに、それを処理するためのヘルパー/拡張メソッドを作成してみませんか。ここでは、要素を返すか、存在しない場合はnullを返します。次に、.exists()の別の拡張メソッドを使用できます。

IWebElement element = driver.FindElmentSafe(By.Id( "the id"));

    /// <summary>
    /// Same as FindElement only returns null when not found instead of an exception.
    /// </summary>
    /// <param name="driver">current browser instance</param>
    /// <param name="by">The search string for finding element</param>
    /// <returns>Returns element or null if not found</returns>
    public static IWebElement FindElementSafe(this IWebDriver driver, By by)
    {
        try
        {
            return driver.FindElement(by);
        }
        catch (NoSuchElementException)
        {
            return null;
        }
    }

ブール値が存在します=element.Exists();

    /// <summary>
    /// Requires finding element by FindElementSafe(By).
    /// Returns T/F depending on if element is defined or null.
    /// </summary>
    /// <param name="element">Current element</param>
    /// <returns>Returns T/F depending on if element is defined or null.</returns>
    public static bool Exists(this IWebElement element)
    {
        if (element == null)
        { return false; }
        return true;
    }
于 2013-08-05T15:15:02.557 に答える
2

このSOの質問からの答えの1つを試すことができます:

public static IWebElement FindElement(this IWebDriver driver, String vList, String vText, int timeoutInSeconds)
{

    By selector = By.Id(ConfigurationManager.AppSettings[vList])
    if (timeoutInSeconds > 0)
    {
        var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
        return wait.Until(drv => drv.FindElement(selector));
    }
    return driver.FindElement(selector);
}
于 2012-06-05T15:02:45.707 に答える
1

ええと、私はJavaの人なので、コードではなく、アルゴリズムを提供します。

  • あなたのコード(私は思う)は、要素が表示されているかどうかを確認し、表示されていない場合は、さらに2.5秒待つ必要があります
  • 失敗する理由は、要素の表示に最初の2.5秒以上かかる場合があるためです。その場合、要素が表示されているかどうかを確認すると、例外がスローされます

したがって、基本的には、forループでいくつかの例外処理を実行し、この例外をキャッチして何もしない必要があります。Javaでは、それはによって実行されtrycatchブロックされます。しかし、私はC#を知らないので、この言語でどのように行われるかを知る必要があります

于 2012-06-05T14:47:32.450 に答える