如何使用 Selenium WebDriver + C# 获取浏览器控制台错误消息
How to get browser console error messages using Selenium WebDriver + C#
我想用Selenium WebDriver + C#收集控制台出现的所有控制台错误信息。我只想要像
这样的控制台错误
控制台错误
按照以下步骤收集浏览器日志,然后输出。
1 - 创建一个收集错误日志的函数
此函数 return 浏览器错误列表。像这样:
private List<string> GetBrowserError()
{
ILogs logs = this.Driver.Manage().Logs;
var logEntries = logs.GetLog(LogType.Browser); // LogType: Browser, Server, Driver, Client and Profiler
List<string> errorLogs = logEntries.Where(x => x.Level == LogLevel.Severe).Select(x => x.Message).ToList();
return errorLogs;
}
2 - 将日志添加到 TestContext
像这样:
private void AddBorwserLogs()
{
string errors = "\n \n*** Errors ***\n \n";
List<string> errorLogs = this.GetBrowserError();
if (errorLogs.Count != 0)
{
foreach (var logEntry in errorLogs)
{
errors = errors + $"{logEntry}\n";
}
// Add errors to TestContext
TestContext.WriteLine($"{errors}\nNumber of browser errors is: {errorLogs.Count}");
}
}
3 - 函数调用
在测试拆卸之前调用 AddBorwserLogs()
函数。像这样:
[TestCleanup]
public void TeardownTest()
{
this.AddBorwserLogs();
this.Driver.Close();
this.Driver.Quit();
}
不要忘记初始化 WebDriver
像这样:
public IWebDriver Driver;
public TestContext TestContext { get; set; }
[TestInitialize]
public void SetupTest()
{
ChromeOptions options = new ChromeOptions();
options.AddArguments("ignore-certificate-errors");
this.Driver = new ChromeDriver(options);
this.Driver.Manage().Timeouts().PageLoad = new TimeSpan(0, 0, 70);
var url = "https://www.selenium.dev/documentation/";
this.Driver.Url = url;
}
我想用Selenium WebDriver + C#收集控制台出现的所有控制台错误信息。我只想要像
这样的控制台错误控制台错误
按照以下步骤收集浏览器日志,然后输出。
1 - 创建一个收集错误日志的函数
此函数 return 浏览器错误列表。像这样:
private List<string> GetBrowserError()
{
ILogs logs = this.Driver.Manage().Logs;
var logEntries = logs.GetLog(LogType.Browser); // LogType: Browser, Server, Driver, Client and Profiler
List<string> errorLogs = logEntries.Where(x => x.Level == LogLevel.Severe).Select(x => x.Message).ToList();
return errorLogs;
}
2 - 将日志添加到 TestContext
像这样:
private void AddBorwserLogs()
{
string errors = "\n \n*** Errors ***\n \n";
List<string> errorLogs = this.GetBrowserError();
if (errorLogs.Count != 0)
{
foreach (var logEntry in errorLogs)
{
errors = errors + $"{logEntry}\n";
}
// Add errors to TestContext
TestContext.WriteLine($"{errors}\nNumber of browser errors is: {errorLogs.Count}");
}
}
3 - 函数调用
在测试拆卸之前调用 AddBorwserLogs()
函数。像这样:
[TestCleanup]
public void TeardownTest()
{
this.AddBorwserLogs();
this.Driver.Close();
this.Driver.Quit();
}
不要忘记初始化 WebDriver
像这样:
public IWebDriver Driver;
public TestContext TestContext { get; set; }
[TestInitialize]
public void SetupTest()
{
ChromeOptions options = new ChromeOptions();
options.AddArguments("ignore-certificate-errors");
this.Driver = new ChromeDriver(options);
this.Driver.Manage().Timeouts().PageLoad = new TimeSpan(0, 0, 70);
var url = "https://www.selenium.dev/documentation/";
this.Driver.Url = url;
}