我正在使用 C#.NET 4 和 Selenium WebDriver 2.44.0.0 和 chromeDriver。 当找不到元素时,Selenium 会抛出错误:
no such element
(Session info: chrome=38.0.2125.104)
(Driver info: chromedriver=2.10.267521,platform=Windows NT 6.1 SP1 x86_64)
但我想知道缺少哪个元素。我看到一些文章说它可以显示这样的详细信息:
OpenQA.Selenium.NoSuchElementException: Unable to locate element: {"method":"id","selector":"hello"}
谁能告诉我如何从 NoSuchElementException 中获取方法和选择器?
这是我的代码
try
{
for(int i=0; i<10; i++)
{
string className = "items-" + i;
IWebElement t = Driver.FindElement(By.CssSelector("[class$='" + className + "'] > span"));
t.Click();
}
}
catch (NoSuchElementException ex)
{
Logger.Error("Error: " + ex.Message);
Debug.WriteLine(ex.Message);
}
最佳答案
By
定位器的 .ToString()
方法返回您所要求的内容。
据我所知,异常本身不包含该信息。不过,处理异常并将其与引发异常的 FindElement()
方法中使用的定位器函数关联起来是很简单的。
例如,如果找不到第 5 次迭代中的元素,下面的代码将产生此消息
Error: no such element
Error: Unable to find element using function By.CssSelector: [class$='items-4'] > span
By locator; // need to declare this outside the scope of the try block
// so it can be accessed in the catch block
try
{
for(int i=0; i<10; i++)
{
string className = "items-" + i;
locatorFunction = By.CssSelector("[class$='" + className + "'] > span")
IWebElement t = Driver.FindElement(locatorFunction);
t.Click();
}
}
catch (NoSuchElementException ex)
{
Logger.Error("Error: " + ex.Message);
Logger.Error("Error: Unable to find element using function " + locatorFunction.ToString());
}
关于C# 如何从 NoSuchElementException 获取方法和选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26628851/