使用 Java 使用 Selenium WebDriver 捕获浏览器日志

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25431380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:22:28  来源:igfitidea点击:

Capturing browser logs with Selenium WebDriver using Java

javaseleniumselenium-webdriver

提问by user3246489

Is there a way to capture browser logs while running automated test cases with Selenium? I found an article on how to capture JavaScript errors in Selenium. But that is just for Firefox and only for errors. I would like to get all the console logs.

有没有办法在使用 Selenium 运行自动化测试用例时捕获浏览器日志?我找到了一篇关于如何在 Selenium 中捕获 JavaScript 错误的文章。但这仅适用于 Firefox,并且仅适用于错误。我想获取所有控制台日志。

采纳答案by Margus

I assume it is something in the lines of:

我认为它是以下几行:

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();
    }
}

Source : Get chrome's console log

来源:获取 chrome 的控制台日志

回答by Johnny

In a more concise way, you can do:

以更简洁的方式,您可以执行以下操作:

LogEntries logs = driver.manage().logs().get("browser");

For me it worked wonderfully for catching JS errors in console. Then you can add some verification for its size. For example, if it is > 0, add some error output.

对我来说,它非常适合在控制台中捕获 JS 错误。然后您可以为其大小添加一些验证。例如,如果它 > 0,则添加一些错误输出。

回答by didinino

A less elegant solution is taking the log 'manually' from the user data dir:

一个不太优雅的解决方案是从用户数据目录“手动”获取日志:

  1. Set the user data dir to a fixed place:

    options = new ChromeOptions();
    capabilities = DesiredCapabilities.chrome();
    options.addArguments("user-data-dir=/your_path/");
    capabilities.setCapability(ChromeOptions.CAPABILITY, options);
    
  2. Get the text from the log file chrome_debug.log located in the path you've entered above.

  1. 将用户数据目录设置为固定位置:

    options = new ChromeOptions();
    capabilities = DesiredCapabilities.chrome();
    options.addArguments("user-data-dir=/your_path/");
    capabilities.setCapability(ChromeOptions.CAPABILITY, options);
    
  2. 从位于您在上面输入的路径中的日志文件 chrome_debug.log 获取文本。

I use this method since RemoteWebDriverhad problems getting the console logs remotely. If you run your test locally that can be easy to retrieve.

我使用这种方法是因为RemoteWebDriver在远程获取控制台日志时遇到问题。如果您在本地运行测试,则可以轻松检索。

回答by Anna

As a non-java selenium user, here is the pythonequivalent to Margus's answer:

作为非 java selenium 用户,这里是相当于 Margus 答案的python

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities    

class ChromeConsoleLogging(object):

    def __init__(self, ):
        self.driver = None

    def setUp(self, ):
        desired = DesiredCapabilities.CHROME
        desired ['loggingPrefs'] = { 'browser':'ALL' }
        self.driver = webdriver.Chrome(desired_capabilities=desired)

    def analyzeLog(self, )
        data = self.driver.get_log('browser')
        print(data)

    def testMethod(self, ):
        self.setUp()
        self.driver.get("http://mypage.com")
        self.analyzeLog()

Reference

参考

Edit: Keeping Python answer in this thread because it is very similar to the Java answer and this post is returned on a Google search for the similar Python question

编辑:在此线程中保留 Python 答案,因为它与 Java 答案非常相似,并且此帖子是在 Google 搜索类似 Python 问题时返回的

回答by phk

Starting with Firefox 65 an about:configflag exists now so console API calls like console.log()land in the output stream and thus the log file (see (https://github.com/mozilla/geckodriver/issues/284#issuecomment-458305621).

从 Firefox 65 开始,about:config现在存在一个标志,因此控制台 API 调用像console.log()输出流中的土地一样,因此是日志文件(参见(https://github.com/mozilla/geckodriver/issues/284#issuecomment-458305621)。

profile = new FirefoxProfile();
profile.setPreference("devtools.console.stdout.content", true);

回答by shiv

Driver manager logs can be used to get console logs from browser and it will help to identify errors appears in console.

驱动程序管理器日志可用于从浏览器获取控制台日志,这将有助于识别控制台中出现的错误。

   import org.openqa.selenium.logging.LogEntries;
   import org.openqa.selenium.logging.LogEntry;

    public List<LogEntry> getBrowserConsoleLogs()
    {
    LogEntries log= driver.manage().logs().get("browser")
    List<LogEntry> logs=log.getAll();
    return logs;
    }

回答by DerWOK

Before launching webdriver, we just set this environment variable to let chrome generate it:

在启动 webdriver 之前,我们只需设置这个环境变量让 chrome 生成它:

export CHROME_LOG_FILE=$(pwd)/tests/e2e2/logs/client.log