如何使用Selenium打开Google Chrome开发者工具中的“网络面板”?

36

我希望能够获得开发工具网络面板上显示的输出结果。

[网络面板 --> 名称、方法、状态、类型、发起者、大小、时间、时间线]

我需要这些信息。


请使用browsermop-proxy。 - Furious Duck
5个回答

37

这可以通过Selenium WebDriver实现。您需要按照以下步骤操作:

  1. http://docs.seleniumhq.org/download/下载特定于语言的Selenium客户端驱动程序,并将相应的jar文件添加到项目构建路径中。

  2. 要使用Chrome / Chromium运行测试,您还需要chromdriver二进制文件,您可以从http://chromedriver.storage.googleapis.com/index.html下载。

  3. 创建如下的测试用例:

    // specify the path of the chromdriver binary that you have downloaded (see point 2)
    System.setProperty("webdriver.chrome.driver", "/root/Downloads/chromedriver");
    ChromeOptions options = new ChromeOptions();
    // if you like to specify another profile
    options.addArguments("user-data-dir=/root/Downloads/aaa"); 
    options.addArguments("start-maximized");
    DesiredCapabilities capabilities = DesiredCapabilities.chrome();
    capabilities.setCapability(ChromeOptions.CAPABILITY, options);
    WebDriver driver = new ChromeDriver(capabilities);
    driver.get("http://www.google.com");
    String scriptToExecute = "var performance = window.performance || window.mozPerformance || window.msPerformance || window.webkitPerformance || {}; var network = performance.getEntries() || {}; return network;";
    String netData = ((JavascriptExecutor)driver).executeScript(scriptToExecute).toString();

在Chrome/Chromium上执行JavaScript将帮助您获取网络(不仅仅是)信息。生成的字符串“netData”将以JSONArray格式包含所需数据。

希望这可以帮助到您。


谢谢,它的表现非常好。有没有选项可以让我们在网络面板中获取传输内容的大小? - Jeevanantham
1
你如何获取传输的总大小?累加transferSize是不准确的。 - Tom Martin
1
请注意,由于CORS的影响,此值可能不准确。https://developer.mozilla.org/en-US/docs/Web/API/Resource_Timing_API/Using_the_Resource_Timing_API#Coping_with_CORS - Tom Martin
4
没有网络,只有性能。那么关于被阻止的资源的信息呢? - sergzach
3
当我尝试这个时,我能够获取前150个网络响应,我该如何获取全部响应详情。 - Ramesh Bala

11

来自这个答案

您可以使用LoggingPreferences获取性能日志。它以json格式返回数据。以下是一个示例Java代码。在Ubuntu 14.04上使用selenium 2.53,chromedriver 2.20,Chrome 50进行了测试。这也应该适用于Windows。

    DesiredCapabilities d = DesiredCapabilities.chrome();
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    d.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
    WebDriver driver = new ChromeDriver(d);
    driver.get("http://www.google.com");
    LogEntries les = driver.manage().logs().get(LogType.PERFORMANCE);
    for (LogEntry le : les) {
        System.out.println(le.getMessage());
    }

这里是一个示例输出。它是手动格式化的。实际输出在一行中。

{
    "message": {
        "method": "Network.requestWillBeSent",
        "params": {
            "documentURL": "https://www.google.co.in/?gfe_rd=cr&ei=gpwxV4OSKMmR2ASEg6-YCg&gws_rd=ssl",
            "frameId": "31172.2",
            "initiator": {
                "stack": {
                    "callFrames": [
                        {
                            "columnNumber": 11511,
                            "functionName": "",
                            "lineNumber": 55,
                            "scriptId": "50",
                            "url": "https://www.google.co.in/?gfe_rd=cr&ei=gpwxV4OSKMmR2ASEg6-YCg&gws_rd=ssl"
                        }
                    ]
                },
                "type": "script"
            },
            "loaderId": "31172.3",
            "request": {
                "headers": {
                    "Accept": "*/*",
                    "Referer": "https://www.google.co.in/",
                    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36"
                },
                "initialPriority": "Low",
                "method": "GET",
                "mixedContentType": "none",
                "url": "https://www.google.co.in/xjs/_/js/k=xjs.s.en.VTDhrkH4c9U.O/m=sx,c,sb,cdos,cr,elog,jsa,r,hsm,qsm,j,p,d,csi/am=AJQ0CwoS8fchIGwhrCA1YGBR/rt=j/d=1/t=zcms/rs=ACT90oGi2YIjVL5cBzOc1-MD37a1NqZ1jA"
            },
            "requestId": "31172.3",
            "timestamp": 251208.074288,
            "type": "Other",
            "wallTime": 1462869123.92204
        }
    },
    "webview": "8AF4A466-8027-4340-B9E9-CFEBDA769C50"
}

10
有没有方法获取响应体? - LINGS
3
我正在寻找一种获取响应体的方法,但似乎不可能。请注意,翻译后的内容将保持与原文意思相同,但更易懂。 - khalil

9
正如其他答案中所提到的那样,您需要使用window.performance方法。以下为相关方法:
getEntries() getEntriesByType() getEntriesByName() Entry Types
例如,在nodejs Selenium-WebDriver测试中,我使用了以下片段来收集Google Analytics网络调用:Chromedriver。
driver
  .executeScript( "return window.performance.getEntriesByType('resource');" )
  .then( (perfEntries)=> {
    let gaCalls = perfEntries.filter(function(entry){
      return /collect\?/i.test(entry.name);
    });
    console.log(gaCalls);
});

如果您使用getEntries()而不是getEntriesByType('resource'),它将返回...所有条目。

谢谢!我使用了脚本 window.performance.getEntriesByName('<exact request name>') 来计算特定的 API 调用次数。这非常有帮助! - Anchal Agrawal

9

假设您想加载一个页面(例如google.com)并提取资源计时对象的数组(即window.performance.getEntries()):

import time
from selenium import webdriver
driver = webdriver.Chrome('/path/to/chromedriver)
driver.get('https://www.google.com');
time.sleep(5)
timings = driver.execute_script("return window.performance.getEntries();")
print timings

6

使用Python的一种方法是:

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import chromedriver_binary # If you're using conda like me.

yoururl = "www.yoururl.com"

caps = DesiredCapabilities.CHROME
caps['goog:loggingPrefs'] = {'performance': 'ALL'}
driver = webdriver.Chrome(desired_capabilities=caps)

driver.get(yoururl)
time.sleep(10) # wait for all the data to arrive. 
perf = driver.get_log('performance')

perf是一个字典列表,您可以在这个列表中找到您需要的项目。 也就是说,字典就是您在Chrome的开发工具网络标签中看到的东西。


还有一件事:从Selenium 4.0开始,它将正式支持访问Chrome devtool网络选项卡信息,但它仍处于beta状态。请查看Selenium存储库以获取更多信息,如果您愿意,可以尝试使用beta来实现相同的目的。 - user8491363
selenium4 鼓励您使用 bidi api: https://www.selenium.dev/documentation/webdriver/bidirectional/bidi_api/ 需要大量改进。 - MortenB

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接