【问题标题】:How to access Network panel on google chrome developer tools with selenium?如何使用硒访问谷歌浏览器开发者工具上的网络面板?
【发布时间】:2013-12-22 11:14:14
【问题描述】:

我想获得在开发者工具的网络面板上显示的输出。

[Network panel --> Name, Method, Status, Type, Initiator, Size, Time, Timeline]

我需要这些信息。

【问题讨论】:

  • 为此使用 browsermop-proxy

标签: networking selenium selenium-webdriver google-chrome-devtools


【解决方案1】:

这可以通过 Selenium WebDriver 实现。为此,您应该执行以下操作:

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

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

  3. 下载它
  4. 像这样创建一个测试用例:

    // 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 格式的所需数据。

希望这会有所帮助。

【讨论】:

  • 感谢它运行良好。有没有什么选项可以让我们从网络面板获取内容传输的大小?
  • 如何获得传输的总大小?加起来 transferSize 不准确
  • 请注意,由于 CORS,此值可能不准确,developer.mozilla.org/en-US/docs/Web/API/Resource_Timing_API/…
  • 没有网络。有表现。被屏蔽资源的信息呢?
  • 当我尝试这个时,我可以获得前 150 个网络响应,我如何获得整个响应详细信息。
【解决方案2】:

假设您要加载一个页面(例如 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

【讨论】:

    【解决方案3】:

    来自this answer

    您可以使用 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"
    }
    

    【讨论】:

    • 有没有办法获取响应正文?
    • 我也在寻找一种获取响应正文的方法。似乎是不可能的。
    【解决方案4】:

    如其他答案所述,您需要使用 window.performance 方法。

    getEntries()
    getEntriesByType()
    getEntriesByName()
    » Entry Types

    例如,我在 nodejs Selenium-WebDriver: Chromedriver 测试中使用了以下 sn-p 来收集 google analytics 网络调用:

    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('') 来计算发出的 API 调用的特定数量。这是最有帮助的!
    【解决方案5】:

    使用 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 存储库以获取更多信息,如果您愿意,请尝试使用测试版实现相同目的。
    猜你喜欢
    • 1970-01-01
    • 2012-08-12
    • 2019-09-15
    • 2013-11-12
    • 2017-12-06
    • 2016-07-02
    • 2018-06-06
    • 1970-01-01
    • 2011-08-07
    相关资源
    最近更新 更多