2017-01-30 10 views
1

har file을 생성하기 위해 netsniff.js의 코드를 사용하고 있으며, 배열 (제공된 코드에서 links)에 제공된 여러 링크에서 har 파일을 생성하도록 개선하려고합니다. .phantom.js를 사용하여 여러 개의 HAR 파일 생성

다음은

내 코드가 나에게 도움이 될 수 있습니다 여기에 Using Multiple page.open in Single Script 또 다른 질문은,하지만 난 어떻게 내 코드에서 주어진 솔루션을 구현하는 아무 생각이

.. (그것은 links 경우 출력 파일에 FAIL to load the address를 기록 배열이 하나 이상의 항목)를 포함 :

"use strict"; 
if (!Date.prototype.toISOString) { 
    Date.prototype.toISOString = function() { 
     function pad(n) { return n < 10 ? '0' + n : n; } 
     function ms(n) { return n < 10 ? '00'+ n : n < 100 ? '0' + n : n } 
     return this.getFullYear() + '-' + 
      pad(this.getMonth() + 1) + '-' + 
      pad(this.getDate()) + 'T' + 
      pad(this.getHours()) + ':' + 
      pad(this.getMinutes()) + ':' + 
      pad(this.getSeconds()) + '.' + 
      ms(this.getMilliseconds()) + 'Z'; 
    } 
} 
var entries = []; 
function createHAR(address, title, startTime, resources) 
{ 
    resources.forEach(function (resource) { 
     var request = resource.request, 
      startReply = resource.startReply, 
      endReply = resource.endReply; 

     if (!request || !startReply || !endReply) { 
      return; 
     } 

     // Exclude Data URI from HAR file because 
     // they aren't included in specification 
     if (request.url.match(/(^data:image\/.*)/i)) { 
      return; 
     } 

     entries.push({ 
      startedDateTime: request.time.toISOString(), 
      time: endReply.time - request.time, 
      request: { 
       method: request.method, 
       url: request.url, 
       httpVersion: "HTTP/1.1", 
       cookies: [], 
       headers: request.headers, 
       queryString: [], 
       headersSize: -1, 
       bodySize: -1 
      }, 
      response: { 
       status: endReply.status, 
       statusText: endReply.statusText, 
       httpVersion: "HTTP/1.1", 
       cookies: [], 
       headers: endReply.headers, 
       redirectURL: "", 
       headersSize: -1, 
       bodySize: startReply.bodySize, 
       content: { 
        size: startReply.bodySize, 
        mimeType: endReply.contentType 
       } 
      }, 
      cache: {}, 
      timings: { 
       blocked: 0, 
       dns: -1, 
       connect: -1, 
       send: 0, 
       wait: startReply.time - request.time, 
       receive: endReply.time - startReply.time, 
       ssl: -1 
      }, 
      pageref: address 
     }); 
    }); 

    return { 
     log: { 
      version: '1.2', 
      creator: { 
       name: "PhantomJS", 
       version: phantom.version.major + '.' + phantom.version.minor + 
        '.' + phantom.version.patch 
      }, 
      pages: [{ 
       startedDateTime: startTime.toISOString(), 
       id: address, 
       title: title, 
       pageTimings: { 
        onLoad: page.endTime - page.startTime 
       } 
      }], 
      entries: entries 
     } 
    }; 
} 
var page = require('webpage').create() 
var fs = require('fs'); 
var count = 0; 
function processSites(links) 
{ 
    page.address = links.pop(); 
    var path = 'file' + count + '.har'; 
    page.resources = []; 
    console.log("page resources:", page.resources) 
    count = count + 1; 
    page.onLoadStarted = function() { 
     page.startTime = new Date(); 
    }; 
    page.onResourceRequested = function (req) { 
     page.resources[req.id] = { 
      request: req, 
      startReply: null, 
      endReply: null 
     }; 
    }; 

    page.onResourceReceived = function (res) { 
     if (res.stage === 'start') { 
      page.resources[res.id].startReply = res; 
     } 
     if (res.stage === 'end') { 
      page.resources[res.id].endReply = res; 
     } 
    }; 

    page.open(page.address, function (status) { 
     var har; 
     setTimeout(function() { 
      if (status !== 'success') { 
       console.log('FAIL to load the address'); 
       phantom.exit(1); 
      } else { 
       page.endTime = new Date(); 
       page.title = page.evaluate(function() { 
        return document.title; 
       }); 
       entries = []; 
       har = createHAR(page.address, page.title, page.startTime, page.resources); 
       // console.log(JSON.stringify(har, undefined, 4)); 
       fs.write(path, JSON.stringify(har), 'w'); 

       if(links.length > 0) 
       { 
        processSites(links); 
       } 
       else 
       { 
        phantom.exit(); 
       } 
      } 
     }, 10000); 
    }); 

} 

var links = ["http://stackoverflow.com", "http://marvel.com"]; 

processSites(links); 

업데이트 :
은 위의 코드는 두 개의 HAR 파일이 file1.har 및 file2.har,하지만 두 번째 HAR 파일도 모두 링크에서 생성 된 har 코드가 포함되어 생성 및 그것은 있어야만한다. 첫 번째 링크에 대한 har 코드 ...

var har = " "

답변

2

당신은 page.open 방법은 비동기이기 때문에 간단한 루프에서 PhantomJS의 페이지를 열어 반복 수를 설정하여이 수정되었습니다. 첫 번째 사이트가 처리 될 때까지 기다리지 않고 바로 두 번째 사이트를 엽니 다.

재귀를 사용하도록 스크립트를 다시 작성했습니다. 다음 사이트는 현재 처리 된 후에 만 ​​열립니다. (참고 : 대기열에있는 사이트 중 하나라도로드에 실패하면 전체 프로세스가 중단되지만이를 방지하기 위해 쉽게 스크립트를 다시 작성할 수 있습니다.

if (!Date.prototype.toISOString) { 
    Date.prototype.toISOString = function() { 
     // ... 
    } 
} 

var entries = []; 

function createHAR(address, title, startTime, resources) 
{ 
    // ... 
} 

var page = require('webpage').create() 

function processSites(links) 
{ 
    page.address = links.pop(); 

    console.log("PAGE ADDRESS: ", page.address); 
    page.resources = []; 

    page.onLoadStarted = function() { 
     page.startTime = new Date(); 
    }; 
    page.onResourceRequested = function (req) { 
     page.resources[req.id] = { 
      request: req, 
      startReply: null, 
      endReply: null 
     }; 
    }; 

    page.onResourceReceived = function (res) { 
     if (res.stage === 'start') { 
      page.resources[res.id].startReply = res; 
     } 
     if (res.stage === 'end') { 
      page.resources[res.id].endReply = res; 
     } 
    }; 

    page.open(page.address, function (status) { 
     var har; 
     setTimeout(function() { 
      if (status !== 'success') { 
       console.log('FAIL to load the address'); 
       phantom.exit(1); 
      } else { 
       page.endTime = new Date(); 
       page.title = page.evaluate(function() { 
        return document.title; 
       }); 
       har = createHAR(page.address, page.title, page.startTime, page.resources); 
       console.log(JSON.stringify(har, undefined, 4)); 

       if(links.length > 0) 
       { 
        processSites(links); 
       } 
       else 
       { 
        phantom.exit(); 
       } 
      } 
     }, 10000); 
    }); 

} 

var links = ["http://edition.cnn.com", "http://stackoverflow.com"]; 

processSites(links); 
+1

''http://edition.cnn.com ''에 대한 har 파일에는''http://stackoverflow.com ''에 대해 생성 된 har 코드도 포함되어 있습니다 ... 개별적으로 하 코드를 출력하는 방법은? – Valip

+1

Vaviloff 당신은 여전히 ​​이것으로 나를 도울 수 있습니까? 나는 그 질문을 갱신했다. 고맙습니다! – Valip

+1

아마도'var entries = [];'는'createHar' 함수 안에 있어야합니까? 실제로 많은 내용을 읽지는 않았지만 질문은 har 파일 자체를 생성하지 않고 링크 배열을 반복하는 것에 관한 것이 었습니다. – Vaviloff