tom*_*tom 5 c# selenium webdriver
我有以下代码用于从给定列表中选择一个选项,它通常可以工作,但有时它会因第二个 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);
}
Run Code Online (Sandbox Code Playgroud)
与其尝试捕获每个实例,不如创建一个帮助程序/扩展方法来为您处理这些问题。这里它返回元素,如果不存在则返回 null。然后你可以简单地为 .exists() 使用另一个扩展方法。
IWebElement 元素 = 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;
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
好吧,我是 Java 人员,所以我不会为您提供代码,而是为您提供算法:
因此,基本上您应该在 for 循环中进行一些异常处理并捕获此异常而不执行任何操作。在 Java 中,它是由try和catch块完成的。但因为我不懂 C#,所以你必须了解它是如何用这种语言完成的
| 归档时间: |
|
| 查看次数: |
9583 次 |
| 最近记录: |