如何使用Selenium提取Chrome开发者工具的网络选项卡内容

3

我一直在尝试编写C#代码,将开发者工具的网络选项卡内容输出为JSONArray,以下是目前的代码:

*IWebDriver driver = new ChromeDriver(@"C:\Users\xxx\Downloads\chromedriver_win32");
driver.Navigate().GoToUrl("https://google.com");
String scriptToExecute = "var performance = window.performance || window.mozPerformance || window.msPerformance || window.webkitPerformance || {}; var network = performance.getEntries() || {}; return network;";
String netData = ((IJavaScriptExecutor)driver).ExecuteScript(scriptToExecute).ToString();
Console.WriteLine(netData);*

另一个:

*IWebDriver driver = new ChromeDriver(@"C:\Users\xxx\Downloads\chromedriver_win32");
driver.Navigate().GoToUrl("https://google.com");
String ste = "Return window.performance.getEntries();";
String Timings = ((IJavaScriptExecutor)driver).ExecuteScript(ste).ToString();
Console.WriteLine(Timings);*

但我的输出没有给出预期的结果。看起来String netData变量返回为空,认为这是脚本问题。 有什么解决方法建议吗?
1个回答

0

你必须意识到ExecuteScript方法的返回类型。如果是JS脚本的情况下

return window.performance.getEntries()

它将会是

IReadOnlyCollection<object>

getEntries()返回一个对象数组 - 在C#代码的情况下,它将是IDictionary<string,object> - 键是JS对象属性名称,值是其值(:)

你必须这样做:

var ste = "return window.performance.getEntries();";
var scriptResult = (IReadOnlyCollection<object>)(IJavaScriptExecutor)driver).ExecuteScript(ste);
var perfEntries = scriptResult.Select(e => ((IDictionary<string, object>)e); 
//(result will be an IEnumerable of IDictionary<string,object>), you can create a new, custom class to convert dictionaries to more verbose objects)

PS请尽量遵循C#约定 ->例如使用string而不是String;使用小写字母命名变量等。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接