提问人:Kristy 提问时间:10/7/2022 更新时间:10/7/2022 访问量:33
在 chromedriver 无头模式下调用 FindElement 时,如何在输出中设置错误?
How can i set an error in output when calling FindElement in chromedriver headless mode?
问:
我在 ChromeDriver 上使用无头模式。 我通过调用找到一个元素
var name= Driver.FindElement(By.Id("TestLabelName"));
if (name== null)
{
}
这里的问题是,如果元素不存在,它只会异常并停止,并且不执行 null 检查。 有没有办法返回元素或只返回 null ? 或者返回控制台窗口数据,而不必将每个 FindElement 都包装在 try catch 周围?
答:
0赞
BouRHooD
10/7/2022
#1
使用 FindElements 而不是 FindElement。
如果未找到匹配的元素,findElements 将返回一个空列表,而不是异常。
复制自: 使用 Selenium WebDriver 测试元素是否存在?
此外,还可以编写一个静态方法来查找元素:
public static IWebElement _FindElement(ChromeDriver inCromeDriver, string inNameElementId)
{
try
{
var name = inCromeDriver.FindElement(By.Id(inNameElementId));
return name;
}
catch (System.Exception ex)
{
System.Console.WriteLine(ex);
return null;
}
}
评论
0赞
Kristy
10/7/2022
有没有类似于 ui 测试中使用的 Assert.Equal 的东西?
0赞
BouRHooD
10/7/2022
@Kristy 是的,你可以编写一个静态方法来查找元素,如果此方法中发生异常,则返回 null
0赞
Kristy
10/7/2022
非常感谢。.所以我假设如果引发异常,我可以调用 Driver.close() 退出控制台吗?并将错误记录到日志文件中?这是最佳实践吗?
评论