gpt4 book ai didi

c# - WebDriver 和 C# - NoSuchElement 异常

转载 作者:行者123 更新时间:2023-11-30 14:14:57 26 4
gpt4 key购买 nike

我有以下代码用于从给定列表中选择一个选项,它通常有效,但有时它会失败并在第二个 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);
}

最佳答案

与其 try catch 每个实例,不如创建一个帮助程序/扩展方法来为您处理。这里它返回元素,如果不存在则返回 null。然后你可以简单地为 .exists() 使用另一种扩展方法。

IWebElement element = driver.FindElmentSafe(By.Id("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;
}
}

bool exists = 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;
}

关于c# - WebDriver 和 C# - NoSuchElement 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10899360/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com