c# - 获取 chrome 的控制台日志

标签 c# javascript asp.net-mvc selenium

我想建立一个自动化测试,所以我必须知道在 chrome 的控制台中出现的错误。

是否有一个选项可以获取出现在控制台中的错误行?

要查看控制台:右键单击页面中的某处,单击“检查元素”,然后转到“控制台”。

最佳答案

我不懂 C#,但这是完成这项工作的 Java 代码,我希望你能将它翻译成 C#

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class ChromeConsoleLogging {
    private WebDriver driver;


    @BeforeMethod
    public void setUp() {
        System.setProperty("webdriver.chrome.driver", "c:\\path\\to\\chromedriver.exe");        
        DesiredCapabilities caps = DesiredCapabilities.chrome();
        LoggingPreferences logPrefs = new LoggingPreferences();
        logPrefs.enable(LogType.BROWSER, Level.ALL);
        caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
        driver = new ChromeDriver(caps);
    }

    @AfterMethod
    public void tearDown() {
        driver.quit();
    }

    public void analyzeLog() {
        LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);
        for (LogEntry entry : logEntries) {
            System.out.println(new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage());
            //do something useful with the data
        }
    }

    @Test
    public void testMethod() {
        driver.get("http://mypage.com");
        //do something on page
        analyzeLog();
    }
}

注意上面代码中的setUp方法。我们使用 LoggingPreferences 对象来启用日志记录。有几种类型的日志,但如果您想跟踪控制台错误,那么您应该使用 LogType.BROWSER。然后我们将该对象传递给 DesiredCapabilities 并进一步传递给 ChromeDriver 构造函数,瞧 - 我们有一个启用了日志记录的 ChromeDriver 实例。

在页面上执行一些操作后,我们调用 analyzeLog() 方法。在这里,我们只是提取日志并遍历其条目。您可以在此处提出断言或进行任何其他您想要的报告。

我的灵感是 this code by Michael Klepikov这解释了如何从 ChromeDriver 中提取性能日志。

关于c# - 获取 chrome 的控制台日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18261338/

相关文章:

c# - JSON.NET - 在运行时排除特定类型的属性

c# - 在运行时创建继承抽象类并实现接口(interface)的类型

javascript - 如何在asp转发器控件中显示模式弹出窗口

c# - 远程验证显示错误消息但仍让表单提交并保存在数据库 MVC 5

c# - 将字符串切成<= 80个字符,并且必须保留单词而不切开它们

javascript - 开 Jest - 没有输出测试结果

javascript - 找不到模块 : internal/modules/cjs/loader. js:969

c# - Visual Studio 2015 中的 MySQL 网站配置失败

.net - mvc路由问题——使用整型参数

c# - 如何阻止变量重置