JavascriptExecutor 之后的 WebElements 列表的 Selenium Web 驱动程序 C# InvalidCastException [英] Selenium Web Driver C# InvalidCastException for List of WebElements after JavascriptExecutor
问题描述
我在 C# 中将 Selenium Web 驱动程序与 Visual Studios 2010 一起使用.我正在使用 jQuery 过滤出一个 div 列表并使用 Selenium 双击它们.但是,无论我做什么,我似乎都无法摆脱 InvalidCastException.
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.
这是我写的代码:
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;
虽然结果确实返回了一个 webelement 列表,但由于某种原因,有时上面的代码运行良好并进行强制转换,而其他时候它不会在 ChromeDriver 上运行.当它不起作用时,提供的最后一行代码失败并显示以下内容:
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]'."
在 InternetExplorerDriver 上,它几乎总是失败并显示以下内容:
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]'.
我已尝试将其转换为 IE 的 RemoteWebElement,但这也不起作用,因为它看到的是 RemoteWebElement 而不是 RemoteWebElement 列表,因此我以后无法枚举它们.
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.
任何关于原因的线索?
推荐答案
我通过执行以下操作使其正常工作:
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!
这篇关于JavascriptExecutor 之后的 WebElements 列表的 Selenium Web 驱动程序 C# InvalidCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!