【发布时间】:2018-12-02 12:01:47
【问题描述】:
范围
我想使用 Selenium 进行自动化 Web 测试并执行 JavaScript。字符串func1 包含我的js 函数,它被传递给ExecuteScript(func1),它返回一个对象数组,看起来像{label:'start', time: 121}。
我想将ExecuteScript 的结果转换成List<timings>
var result = jsExecutor.ExecuteScript(func1);
var list = (ReadOnlyCollection<object>)result;
var timings = (List<Timing>)list;
我收到了错误
Cannot convert type 'System.Collections.ObjectModel.ReadOnlyCollection<object>'
to 'System.Collections.Generic.List<CoreConsoleApp.TestExecutions.Timing>'
这是 func1
string func1= @"var t = window.performance.timing;
var timings = [];
timings.push({ label: 'navigationStart', time: t.navigationStart });
timings.push({ label: 'PageLoadTime', time: t.loadEventEnd - t.navigationStart });
return timings;" // result is an array of js-objects
下面的代码是硒部分的sn-p
public struct Timing
{
public string label;
public int time;
}
using (var driver = new FirefoxDriver())
{
...
var jsExecutor = (IJavaScriptExecutor)driver;
var result = jsExecutor.ExecuteScript(func1);
var list = (ReadOnlyCollection<object>)result;
}
问题
selenium 文档声明 ExecuteScript attempts to return a List 用于数组。
Func1 应该返回数组 {label: string, time: number} 它应该很容易将结果 var list = (ReadOnlyCollection<object>)result 转换为 List<string,int> timings = (List<timings>)list;
- 如何将“System.Collections.ObjectModel.ReadOnlyCollection”转换为 List?
更多信息
启动火狐var driver = new FirefoxDriver()打开一个URLdriver.Navigate().GoToUrl(url);找到某个按钮IWebElement button = driver.FindElement(By.Name("btnK"));提交表单button.Submit();提交后执行JavaScriptExecuteScript(func1)并将结果写入控制台
以上所有工作。但我无法将 JavaScript 转换为 c# 对象列表。
所以我的解决方法是这样的
var result = jsExecutor.ExecuteScript(func1);
var list = (ReadOnlyCollection<object>)result;
foreach (object item in list)
{
var timing = (Dictionary<string, object>)item;
foreach(KeyValuePair<string, object> kvp in timing)
{
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
}
这就出来了:
Key = label, Value = navigationStart
Key = time, Value = 1529720672670
Key = label, Value = PageLoadTime
Key = time, Value = 1194
Key = label, Value = DOMContentLoadedTime
Key = time, Value = 589
Key = label, Value = ResponseTime
【问题讨论】:
标签: javascript c# selenium .net-core