我可以以编程方式获取Chrome Devtools Performance信息吗?

时间:2017-11-15 20:27:22

标签: javascript google-chrome google-chrome-devtools

我喜欢chrome devtools性能标签信息,但我希望能够在自动功能测试期间记录性能配置文件。我可以执行javascript来获取初始加载性能数据(window.performance),我正在寻找的是获取性能配置文件信息的内容。简单的事情,如网络通话的持续时间和个人资料摘要。

类似的东西:

events =[
  { type: Network request,
    URL: someURL,
    Duration: 431.43 ms,
    Request Method: POST,
    Priority: High,
    Mime Type: application/json,
    Encoded Data: 544 B,
    Decoded Body: 50 B,
    Initiator: JavascriptInsert.js:49
  },
  {
    type: Network request,
    URL: someOtherURL,
    Duration: 81.50 ms,
    Request Method: POST,
    Priority: High,
    Mime Type: text/plain,
    Encoded Data: 260 B,
    Initiator: angular.js:10514  
  }
]

summary= {
  Loading: 2.5ms,
  Scripting: 587.6ms,
  Rendering: 77.6ms,
  Painting: 52.5ms,
  Other: 109.3ms,
  Idle: 3040.1ms
}

2 个答案:

答案 0 :(得分:1)

如果您使用的是Selenium,请使用browser.get_log获取所有效果日志。我的解决方案使用Python,但对于任何支持的语言都应该类似。

首先,设置无头Chrome:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = webdriver.ChromeOptions()
chrome_options.set_headless(True)

# for possible entries refer to current implementation at
# https://chromium.googlesource.com/chromium/src/+/master/chrome/test/chromedriver/capabilities.cc#372
perfLogPrefs = {
    "traceCategories": "toplevel,disabled-by-default-devtools.timeline.frame,blink.console,disabled-by-default-devtools.timeline,benchmark"
}
chrome_options.add_experimental_option("perfLoggingPrefs", perfLogPrefs)

desired_capabilities = chrome_options.to_capabilities()
desired_capabilities['loggingPrefs'] = {
    "browser": "ALL",  # use this for console.log output, and obtain later
    "performance": "ALL",
}

browser = webdriver.Chrome(
    chrome_options=chrome_options,
    desired_capabilities=desired_capabilities)

测试完成后,使用get_log获取日志并提取条目:

# based more or less on
# https://sites.google.com/a/chromium.org/chromedriver/logging/performance-log#TOC-Collecting-Log-Entries
import json
with open(base_filename + '.perf.log', 'w') as f:
    logs = browser.get_log('performance')
    f.write('[')
    add_comma = False
    for entry in logs:
        if add_comma:
            f.write(',\n')
        message = json.loads(entry['message'])['message']
        json.dump(message['params'], f)
        add_comma = True
    f.write(']')

条目类似于Trace Event Format documentation中描述的条目。但是,我无法找到适当的文件格式,以便稍后在Chrome DevTools Performance标签中加载它。我收到一个错误:

Malformed timeline data: TypeError: Cannot read property 'split' of undefined

如果有人设法在Chrome中加载,请更新我的回答(或在How to visualize log of chrome DevTool protocol messages?中发帖回答)。

答案 1 :(得分:1)

网络呼叫的持续时间和类似的详细信息也可在window.performance interface中找到。您可以使用performance.getEntriesByType("resource")获取您网页所有请求的条目。