Export HAR using chromedriver

后端 未结 3 717
深忆病人
深忆病人 2021-02-14 18:07

Is it possible to export HAR using chromedriver similar to what I can do with netexpert+firebug with Firefox?

3条回答
  •  [愿得一人]
    2021-02-14 18:32

    Please checkout the code at

    https://gist.github.com/Ankit3794/01b63199bd7ed4f2539a088463e54615#gistcomment-3126071

    Steps:

    Initiate ChromeDriver instance with enabling Logging Preference

    DesiredCapabilities capabilities = DesiredCapabilities.chrome();
    ChromeOptions chromeOptions = new ChromeOptions();
    chromeOptions.addArguments("ignore-certificate-errors");
    chromeOptions.addArguments("disable-infobars");
    chromeOptions.addArguments("start-maximized");
    
    // More Performance Traces like devtools.timeline, enableNetwork and enablePage
    Map perfLogPrefs = new HashMap<>();
    perfLogPrefs.put("traceCategories", "browser,devtools.timeline,devtools");
    perfLogPrefs.put("enableNetwork", true);
    perfLogPrefs.put("enablePage", true);
    chromeOptions.setExperimentalOption("perfLoggingPrefs", perfLogPrefs);
    
    // For Enabling performance Logs for WebPageTest
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
    capabilities.setCapability("goog:loggingPrefs", logPrefs);
    capabilities.merge(chromeOptions);
    

    Get "message" JSONObject from Performance Logs

    private static JSONArray getPerfEntryLogs(WebDriver driver) {
        LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);
        JSONArray perfJsonArray = new JSONArray();
        logEntries.forEach(entry -> {
            JSONObject messageJSON = new JSONObject(entry.getMessage()).getJSONObject("message");
            perfJsonArray.put(messageJSON);
        });
        return perfJsonArray;
    }
    

    Get HAR by passing PerfLogs

    public static void getHAR(WebDriver driver, String fileName) throws IOException {
        String destinationFile = "/HARs/" + fileName + ".har";
        ((JavascriptExecutor) driver).executeScript(
                "!function(e,o){e.src=\"https://cdn.jsdelivr.net/gh/Ankit3794/chrome_har_js@master/chromePerfLogsHAR.js\",e.onload=function(){jQuery.noConflict(),console.log(\"jQuery injected\")},document.head.appendChild(e)}(document.createElement(\"script\"));");
        File file = new File(destinationFile);
        file.getParentFile().mkdirs();
        FileWriter harFile = new FileWriter(file);
        harFile.write((String) ((JavascriptExecutor) driver).executeScript(
                "return module.getHarFromMessages(arguments[0])", getPerfEntryLogs(driver).toString()));
        harFile.close();
    }
    

提交回复
热议问题