使用puppetter生成har

时间:2018-04-09 12:58:57

标签: node.js headless-browser puppeteer har

我可以使用chrome扩展程序在任何网站上记录用户事件(点击,输入值),并可以保存步骤并在mongodb中启动网址。我想重播那些记录的步骤并为每个新请求生成HAR。

记录的步骤格式: 单击

{
  "_id": ObjectId("5ac9f48c9963508c33b83183"),
  "target": "button.btn-sm",
  "command": "click",
  "sequence": 0,
  "recording_id": ObjectId("5ac9f48c9963508c33b83182"),
  "__v": 0
}  

输入

{
  "_id": ObjectId("5ac9f48c9963508c33b83184"),
  "target": "input[name=\"email\"]",
  "command": "assign",
  "value": "atul@impulsiveweb.com",
  "sequence": 1,
  "recording_id": ObjectId("5ac9f48c9963508c33b83182"),
  "__v": 0
}.

生成har的当前代码: - >

    const puppeteer = require('puppeteer');
    const { harFromMessages } = require('chrome-har');
    // list of events for converting to HAR
    const events = [];
    // event types to observe
    const observe = [
        'Page.loadEventFired',
        'Page.domContentEventFired',
        'Page.frameStartedLoading',
        'Page.frameAttached',
        'Network.requestWillBeSent',
        'Network.requestServedFromCache',
        'Network.dataReceived',
        'Network.responseReceived',
        'Network.resourceChangedPriority',
        'Network.loadingFinished',
        'Network.loadingFailed',
    ];
    export default async (id,obj) => {
        const browser = await puppeteer.launch();
        const page = await browser.newPage();

    // register events listeners
        const client = await page.target().createCDPSession();
        await client.send('Page.enable');
        await client.send('Network.enable');
        observe.forEach(method => {
            client.on(method, params => {
                events.push({ method, params });
            });
        });
        // perform tests

    const steps = await RecordingSteps.find({recording_id:id}).sort({ sequence: 1 });
        const recording = await Recording.findById(id);
        await page.goto(recording.recording.startUrl);
          for(let i = 0; i < steps.length; i++){
            if(steps[i].command === 'click'){
              await page.click(steps[i].target);
              if(i < steps.length -1){
                await page.waitFor(steps[i+1].target)
              }
            }else if(steps[i].command === 'assign'){
              await page.click(steps[i].target);
              await page.keyboard.type(steps[i].value);
            } //convert events to HAR file
            const har = harFromMessages(events);
await promisify(fs.writeFile)(`${config.storage.file.har1}${i}.har`,JSON.stringify(har))
}}

以上代码在从db获取的每一步(无论是单击还是分配值)上生成har,但我希望在任何请求更改后生成例如: - ajax请求或URL更改。

感谢名单。

1 个答案:

答案 0 :(得分:0)

我使用Chrome开发工具协议-https://github.com/loadmill/har-recorder/blob/master/index.js

实施了此操作

我将其包装在一个小的npm模块中,以将硒测试捕获为HAR文件-https://www.npmjs.com/package/har-recorder,但这也适用于Puppeteer。