【问题标题】:How to read the Web Browser Console in Selenium?如何阅读 Selenium 中的 Web 浏览器控制台?
【发布时间】:2016-07-18 03:47:15
【问题描述】:

我使用的是 Selenium 版本 2.46.0。 为了调试不同的问题(例如客户端问题),我想获取所有 Web 浏览器控制台内容(错误、警告...)

我尝试使用:

LogEntries logs1 = DefaultDriver.getWebDriver().manage().logs().get("client");

但是得到了空的日志条目...

顺便说一句,我定义了功能:

capabilities = DesiredCapabilities.firefox();
LoggingPreferences logs = new LoggingPreferences();
logs.enable( LogType.CLIENT, Level.ALL );
capabilities.setCapability( CapabilityType.LOGGING_PREFS, logs );
webDriver = new FirefoxDriver( capabilities );

我还尝试了“驱动程序”和“浏览器”日志类型,但没有获得 Web 控制台内容。

知道怎么做吗?

以下链接中的解决方案无效... Capturing browser logs with Selenium

【问题讨论】:

  • @Eugene,该链接中描述的解决方案不起作用
  • 你需要.get(LogType.BROWSER) 不需要 .get("client")。您的代码的功能部分很好。

标签: java selenium selenium-webdriver selenium-chromedriver


【解决方案1】:

我不确定这是否可行。 但是您可以尝试使用以下内容打开控制台

Actions builder = new Actions(pbDriver); builder.keyDown(Keys.CONTROL).sendKeys(Keys.F12).keyUp(Keys.CONTROL).perform();

然后使用 selenium 与控制台交互。

或,

您可以通过“手动”从用户数据目录获取日志来尝试不太优雅的解决方案:

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

    options = new ChromeOptions(); capabilities = DesiredCapabilities.chrome(); options.addArguments("user-data-dir=/your_path/"); capabilities.setCapability(ChromeOptions.CAPABILITY, options);

  2. 从您在上面输入的路径中的日志文件 chrome_debug.log 中获取文本

编辑:

我实际上尝试了问题中提到的方法,它对我有用。我使用的浏览器是 Chrome。正如Siking 指出的那样,我已经使用 .enable(LogType.BROWSER) 来获取日志。 以下代码确实打印了整个运行期间捕获的所有日志。

LogEntries logEntries = pbDriver.manage().logs().get("browser"); for (LogEntry entry : logEntries) { System.out.println(entry.getMessage());

我刚刚了解到,由于开发人员工具不是 DOM 模型的一部分,因此无法使用 selenium 与之交互。 Sikuli 可以用来做这个工作

【讨论】:

  • "... 使用 selenium 与控制台交互" 你能举个例子吗?
【解决方案2】:

你可以试试这个:

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

def get_logs2(driver):
# enable browser logging
    #d = DesiredCapabilities.CHROME
    #d['goog:loggingPrefs'] = { 'browser':'ALL' }
    #driver = webdriver.Chrome(desired_capabilities=d)

    # load the desired webpage
    #driver.get('http://34.90.50.21/')
    #driver.get(driver.current_url)
    a = driver.get_log('browser')

    # print messages
    for entry in driver.get_log('browser'):
        print(entry)
    print("finished")
    return a

或检查:Robot Frameworkget background call with Robot Framework/selenium

【讨论】:

    【解决方案3】:

    我在 C# 中遇到了与 selenium 相同的问题,我想向您展示我的解决方法,它适用于每个浏览器(在 C# 中)

    首先,我将网站生成的所有日志重定向到存储所有日志的数组。 我还重定向 onerror 函数以收集所有 javascript 错误

        private void BindConsole(IWebDriver webDriver)
      {
         var script = "if (console.everything === undefined) {
            console.everything = [];
            console.defaultLog = console.log.bind(console);
            console.log = function(){
               const args = Array.prototype.slice.call(arguments).join('_');
               console.everything.push({ 'Type':'Log', 'Datetime':Date().toLocaleString(), 'Value':args});
               console.defaultLog.apply(console, arguments);
            }
            console.defaultError = console.error.bind(console);
            console.error = function(){
               const args = Array.prototype.slice.call(arguments).join('_');
               console.everything.push({ 'Type':'Error', 'Datetime':Date().toLocaleString(), 'Value':args});
               console.defaultError.apply(console, arguments);
            }
            console.defaultWarn = console.warn.bind(console);
            console.warn = function(){
               const args = Array.prototype.slice.call(arguments).join('_');
               console.everything.push({ 'Type':'Warn', 'Datetime':Date().toLocaleString(), 'Value':args});
               console.defaultWarn.apply(console, arguments);
            }
            console.defaultDebug = console.debug.bind(console);
            console.debug = function(){
               const args = Array.prototype.slice.call(arguments).join('_');
               console.everything.push({ 'Type':'Debug', 'Datetime':Date().toLocaleString(), 'Value':args});
               console.defaultDebug.apply(console, arguments);
            }
            window.onerror = function(message, url, linenumber) {
               console.error('JavaScript error: ' + message + ' on line ' +
               linenumber + ' for ' + url);
               }
            }";
    
         ((IJavaScriptExecutor)webDriver).ExecuteScript(script);
      }
    

    注意:您需要在测试前运行此函数,因为不会捕获日志,并且每次刷新或更改页面时都重新运行它(刷新/更改时所有日志都会丢失,因此请提前保存)

    然后,我的函数中有与日志签名匹配的对象

     public class LogEntry
       {
          public LogType Type { get; set; }
          public string Datetime { get; set; }
          public string Value { get; set; }
       }
    
     public enum LogType
       {
          Error,
          Warn,
          Log,
          Debug
       }
    

    然后我运行以下函数:

     /// <summary>
      /// Check whether new blogs are in browser console and captures them if any. 
      /// </summary>
      /// <returns>Logs from browser console</returns>
      public IEnumerable<LogEntry> GetAllConsoleLogs()
      {
         SystemTools.Delay();
    
         var jsScript = "return console.everything";
         var list = ((IJavaScriptExecutor)_driver.Driver).ExecuteScript(jsScript) as IReadOnlyCollection<object>;
         if (list!=null && list.Count > 0) {
            var token = JArray.FromObject(list);
            ClearConsole();
            return token.ToObject<IEnumerable<LogEntry>>();
         } else {
            return null;
         }
      }
      
    
      /// <summary>
      /// Delete all previous entrys form browser console, so only new ones will be captured
      /// </summary>
      private void ClearConsole()
      {
         var jsScript = "console.everything =[];";
         ((IJavaScriptExecutor)_driver.Driver).ExecuteScript(jsScript);
      }
    

    此函数采用带有日志 (Json) 的数组,并在 .NET Json 库的帮助下将其转换为 C# 对象。 每次记录日志时我都会清除对象,因为我只想检查新对象,如果此行为不适合您,您可以删除此函数的调用并保留所有测试的日志

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-26
      • 1970-01-01
      • 2019-07-02
      • 2020-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-31
      相关资源
      最近更新 更多