1. 程式人生 > >使用chrome-har導出瀏覽器HAR數據

使用chrome-har導出瀏覽器HAR數據

-i each line 錯誤 ret 經驗 session ring tool

這裏使用nodejs下的chrome-har庫來導出瀏覽器的har數據,經驗證效果不錯,比較靠譜。

const fs = require(‘fs‘);
const { promisify } = require(‘util‘);

const puppeteer = require(‘puppeteer‘);
const { harFromMessages } = require(‘chrome-har‘);

// 設置要監控的事件
const observe = [
  ‘Page.loadEventFired‘,
  ‘Page.domContentEventFired‘,
  ‘Page.frameStartedLoading‘,
  ‘Page.frameAttached‘,
  ‘Network.requestWillBeSent‘,
  ‘Network.requestServedFromCache‘,
  ‘Network.dataReceived‘,
  ‘Network.responseReceived‘,
  ‘Network.resourceChangedPriority‘,
  ‘Network.loadingFinished‘,
  ‘Network.loadingFailed‘,
];

/*
    啟動瀏覽器
*/ 
async function launchBrowser(){
    //啟動瀏覽器實例 [puppeteer.createBrowserFetcher([options])]
  let browser = await puppeteer.launch({
    // 若是手動下載的chromium需要指定chromium地址, 默認引用地址為 /項目目錄/node_modules/puppeteer/.local-chromium/
    //executablePath: ‘/Users/huqiyang/Documents/project/z/chromium/Chromium.app/Contents/MacOS/Chromium‘,
    //如果是訪問https頁面 此屬性會忽略https錯誤
    ignoreHTTPSErrors: true,
    // 關閉headless模式, 不會打開瀏覽器
    headless: false,
    //瀏覽器啟動參數 https://peter.sh/experiments/chromium-command-line-switches/   --timeout
    args:["--disk-cache-size=0","--disable-cache",‘--disable-infobars‘,‘--window-size=800,600‘,‘--ignore-certificate-errors‘,‘--enable-feaures‘],
    //是否為每個選項卡自動打開DevTools面板。 如果此選項為true,則headless選項將設置為false。
    devtools: true,
    //Defaults to 30000 (30 seconds). Pass 0 to disable timeout.
    timeout: 0,
    //放慢puppeteer執行的動作,方便調試
    slowMo: 250
  });
  return browser ;
}

async function saveHarlog(url,filename){
  //打開瀏覽器
  let browser = await launchBrowser() ;

  //創建一個新頁面
  //let page = await browser.newPage();
  let page = (await browser.pages())[0];

  // 註冊事件監聽器
  const client = await page.target().createCDPSession();
  await client.send(‘Page.enable‘);
  await client.send(‘Network.enable‘);

  //用於保存用於轉為為HAR數據的事件
    const events = [];
  observe.forEach(method => {
    client.on(method, params => {
      events.push({ method, params });
    });
  });

  try{
    // 執行跳轉,訪問制定的資源
    await page.goto(url,{
            timeout:0
    });
  }catch(error){
    console.log(‘resovle error :‘ + url + ";  error message:" + error) ;
  }finally{
    if(browser){
        await browser.close();      
    }
  } 
  const har = harFromMessages(events);
  await promisify(fs.writeFile)(filename + ‘.har‘, JSON.stringify(har));

}
exports.launchBrowser = launchBrowser;
exports.saveHarlog = saveHarlog;

//測試
try{
    saveHarlog(‘http://www.baidu.com‘,‘www.baidu.com‘) ;    
}catch(error){}

參考地址:https://michaljanaszek.com/blog/generate-har-with-puppeteer

使用chrome-har導出瀏覽器HAR數據