【问题标题】:Selenium IWebElement to PhantomJSWebElementSelenium IWebElement 到 PhantomJSWebElement
【发布时间】:2014-01-14 19:37:12
【问题描述】:

我在我的 C# 项目中使用 Ghost 驱动程序 (PhantomJS)。我有个问题。 Selenium 有 PhantomJSWebElement 和 PhantomJSDriver。 我正在创建 PhantomJSDriver

PhantomJSDriverService service = PhantomJSDriverService.CreateDefaultService();
service.IgnoreSslErrors = true;
service.LoadImages = false;
service.Start();
PhantomJSDriver ghostDriver = new PhantomJSDriver(service);

然后尝试通过 xpath 查找元素

List<string> retVal = new List<string>();
var aElements = ghostDriver.FindElementsByXPath("//div[@id='menu']//a[@href]");
foreach(PhantomJSWebElement link in aElements)
{
   try
   {
      retVal.Add(link.GetAttribute("href"));
   }
   catch (Exception)
   {
      continue;
   }
}

所以我在将IWebElemet 转换为PhantomJSWebElement 时出错。

PhantomJSWebElement el = (PhantomJSWebElement)link; 

也不起作用(抛出转换异常)。那么问题来了,如何通过 PhantomJSDriver 获取 PhantomJSWebElement 在查找时只返回 IWebElement(或它们的集合)。

【问题讨论】:

  • 如果不发布确切的异常文本,这个问题很难回答。另外,你有没有用你的调试器处理过这个异常? type 是什么link
  • 我在 VS 上有俄语版。文本为:Не удалось привести тип объекта "OpenQA.Selenium.Remote.RemoteWebElement" к типу "OpenQA.Selenium.PhantomJS.PhantomJSWebElement"。它在 aElements 中的 PhantomJSWebElement 链接处抛出
  • 我认为link 的类型是WebElementPhantomJSWebElement 继承自 RemoteWebElement。您是否尝试过像这样投射:PhantomJSWebElement el = (RemoteWebElement)link;
  • 哪里没有WebElement。 PhantomJSWebElement 继承自 RemoteWebElement
  • 双重转换像 (PhantomJSWebElement)(RemoteWebElement) 有同样的例外。

标签: c# selenium xpath ghostdriver


【解决方案1】:

一般来说,在使用 .NET 绑定时,您不应该使用特定于浏览器的类。相反,您应该对您期望的接口进行编码。这允许您根据需要替换不同的实现。您的代码将如下所示:

PhantomJSDriverService service = PhantomJSDriverService.CreateDefaultService();
service.IgnoreSslErrors = true;
service.LoadImages = false;

// Not sure I'd use Start here. The constructor will start the service
// for you.
service.Start();

// Use the IWebDriver interface. There's no real advantage to using
// the PhantomJSDriver class.
IWebDriver ghostDriver = new PhantomJSDriver(service);

// ...

List<string> retVal = new List<string>();
var aElements = ghostDriver.FindElements(By.XPath("//div[@id='menu']//a[@href]"));

// Use the IWebElement interface here. The concrete PhantomJSWebElement
// implementation gives you no advantages over coding to the interface.
foreach(IWebElement link in aElements)
{
    try
    {
        retVal.Add(link.GetAttribute("href"));
    }
    catch (Exception)
    {
        continue;
    }
}

您还应该注意,类文档很可能不正确。了解语言绑定的源代码后,PhantomJSWebElement 类从未在任何地方实际实例化。我相信你实际上从你的FindElements() 调用中得到的是RemoteWebElements,所以试图将它们从继承层次结构中转换为更具体的子类注定要失败。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 2015-02-13
    • 2022-01-01
    • 1970-01-01
    • 2014-03-08
    相关资源
    最近更新 更多