Reputation: 101
I'm using Selenium web driver with Visual Studios 2010 in C#. I'm using a jQuery to filter out a list of divs and use Selenium to double click them. However, no matter what I do, I can't seem to get rid of the InvalidCastException.
Here is the code that I wrote:
IWebDriver m_driver = new ChromeDriver();
IJavaScriptExecutor js = m_driver as IJavaScriptExecutor;
string jsQuery = [insert some query here that returns list of divs];
object result = js.ExecuteScript(jsQuery);
System.Collections.ObjectModel.ReadOnlyCollection<IWebElement> list = (System.Collections.ObjectModel.ReadOnlyCollection<IWebElement>)result;
The result does return a list of webelements though, but for some reason, sometimes the code above runs fine and casts and other times it doesn't on ChromeDriver. When it doesn't work, the last line of code provided fails with the following:
"Unable to cast object of type 'System.Collections.ObjectModel.ReadOnlyCollection`1[System.Object]' to type 'System.Collections.ObjectModel.ReadOnlyCollection`1[OpenQA.Selenium.IWebElement]'."
On InternetExplorerDriver, it fails almost all the time with the following:
Unable to cast object of type 'OpenQA.Selenium.Remote.RemoteWebElement' to type 'System.Collections.ObjectModel.ReadOnlyCollection`1[OpenQA.Selenium.IWebElement]'.
I have tried casting it to RemoteWebElement for IE, but that doesn't work either, because it sees RemoteWebElement and not a list of RemoteWebElements, and hence I can't enumerate them later.
Any clues as to why?
Upvotes: 1
Views: 6452
Reputation: 101
I got it to work by doing the following:
IWebDriver m_driver = new ChromeDriver();
IJavaScriptExecutor js = m_driver as IJavaScriptExecutor;
string jsQuery = [insert some query here that returns list of divs];
var result = js.ExecuteScript(jsQuery);
foreach (IWebElement element in (IEnumerable) result){...}
This works and no longer throws exceptions!
Upvotes: 2
Reputation: 7372
Why won't you just use driver.findElements(By.xpath())
?
Any particular reason that you have to go through jQuery?
To get the actual elements from the jQuery list you'll probably have to use .toArray()
Upvotes: 0
Reputation: 27496
Make sure that the objects you're returning from you JavaScript are actual HTML elements, and not jQuery-wrapped objects. jQuery may be wrapping the elements inside its own objects, which means that the objects returned from your JavaScript execution aren't actually IWebElements
.
As an aside, it's not often that it makes sense to use JavaScript for element location. It might be worth an explanation as to why you can't simply use FindElements()
for your purposes.
Upvotes: 0