Question

Im using Ghost Driver (PhantomJS) in my C# project. I have a question. Selenium has PhantomJSWebElement and PhantomJSDriver. Im creating PhantomJSDriver

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

And then trying to find elements by 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;
   }
}

So i have an error while casting IWebElemet to PhantomJSWebElement.

PhantomJSWebElement el = (PhantomJSWebElement)link; 

also not works (throwing casting exception). So the question is, how to get PhantomJSWebElement by PhantomJSDriver returns only IWebElement (or a collection of them) while finding.

Was it helpful?

Solution

In general, you should not be using the browser-specific classes when using the .NET bindings. Instead, you should be coding to the interfaces that you expect. This allows you to substitute in different implementations as needed. Your code would look something like this:

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;
    }
}

You should also note that there is every possibility that the class documentation is incorrect. Knowing the source code for the language bindings, the PhantomJSWebElement class is never actually instantiated anywhere. I believe what you're actually getting back from your FindElements() call are RemoteWebElements, so attempting to cast them down the inheritance hierarchy to the more specific subclass is doomed to failure.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top