gpt4 book ai didi

c# - 使用 selenium 读取浏览器日志时出现 System.NullReferenceException

转载 作者:太空狗 更新时间:2023-10-29 23:35:55 32 4
gpt4 key购买 nike

我正在使用 C#selenium chromeWebDriver 编写。当我尝试使用 selenium 读取浏览器控制台日志文件时,我得到:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

private void button1_Click(object sender, EventArgs e)
{
ChromeOptions options = new ChromeOptions();
options.SetLoggingPreference(LogType.Browser, LogLevel.Warning);
IWebDriver driver = new ChromeDriver(options);

driver.Url = "https://www.google.com/";

var entries = driver.Manage().Logs.GetLog(LogType.Browser); // System.NullReferenceException
foreach (var entry in entries)
{
Console.WriteLine(entry.ToString());
}
}

enter image description here

最佳答案

这是我在 Selenium 4 推出之前的解决方案(也适用于 Selenium 4)。它快速而肮脏,旨在演示如何完成。随意更改和改进。

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Remote;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Reflection;
using System.Text;

namespace GetChromeConsoleLog
{
internal static class Program
{
private static void Main()
{
// setup options
var options = new ChromeOptions();
options.SetLoggingPreference(LogType.Browser, LogLevel.All);

// do whatever actions
var driver = new ChromeDriver(options)
{
Url = "https://www.yahoo.com/"
};

var logs = driver.GetBrowserLogs();

// extract logs (using the extension method GetBrowserLogs)
foreach (var log in driver.GetBrowserLogs())
{
Console.WriteLine($"{log["timestamp"]}: {log["message"]}");
}

// cleanup
driver.Dispose();

// hold console
Console.WriteLine();
Console.WriteLine("Press any key to exit...");
Console.ReadLine();
}
}

public static class WebDriverExtensions
{
public static IEnumerable<IDictionary<string, object>> GetBrowserLogs(this IWebDriver driver)
{
// not a chrome driver
if(driver.GetType() != typeof(ChromeDriver))
{
return Array.Empty<IDictionary<string, object>>();
}

// setup
var endpoint = GetEndpoint(driver);
var session = GetSession(driver);
var resource = $"{endpoint}session/{session}/se/log";
const string jsonBody = @"{""type"":""browser""}";

// execute
using (var httpClient = new HttpClient())
{
var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
var response = httpClient.PostAsync(resource, content).GetAwaiter().GetResult();
var responseBody = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
return AsLogEntries(responseBody);
}
}

private static string GetEndpoint(IWebDriver driver)
{
// setup
const BindingFlags Flags = BindingFlags.Instance | BindingFlags.NonPublic;

// get RemoteWebDriver type
var remoteWebDriver = GetRemoteWebDriver(driver.GetType());

// get this instance executor > get this instance internalExecutor
var executor = remoteWebDriver.GetField("executor", Flags).GetValue(driver) as ICommandExecutor;

// get URL
var uri = executor.GetType().GetField("remoteServerUri", Flags).GetValue(executor) as Uri;

// result
return uri.AbsoluteUri;
}

private static Type GetRemoteWebDriver(Type type)
{
if (!typeof(RemoteWebDriver).IsAssignableFrom(type))
{
return type;
}

while (type != typeof(RemoteWebDriver))
{
type = type.BaseType;
}

return type;
}

private static SessionId GetSession(IWebDriver driver)
{
if (driver is IHasSessionId id)
{
return id.SessionId;
}
return new SessionId($"gravity-{Guid.NewGuid()}");
}

private static IEnumerable<IDictionary<string, object>> AsLogEntries(string responseBody)
{
// setup
var value = $"{JToken.Parse(responseBody)["value"]}";
return JsonConvert.DeserializeObject<IEnumerable<Dictionary<string, object>>>(value);
}
}
}

get logs

关于c# - 使用 selenium 读取浏览器日志时出现 System.NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57209503/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com