C# 如何从 NoSuchElementException 获取方法和选择器

标签 c# selenium selenium-webdriver

我正在使用 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/

相关文章:

java - 如何使用机器人类在 Selenium 中基于 webelement 而不是 getlocation 的 xy 坐标执行 mousemove?

c# - 通过 javascript 从 View 渲染页面

c# - 桥梁模式与策略模式

c# - 在 .NET Standard 库中使用动态

python - 我的抓取工具无法从网页获取所有项目

selenium-webdriver - WebdriverIO - 如何向 Jasmine 测试发送参数?

c# - 在表单 View 中设置当前日期

selenium - Selenium WebDriver 可以在后台静默打开浏览器窗口吗?

Python selenium 在显示时单击元素

python - 如何允许或拒绝通知地理位置麦克风摄像头弹出