WebPageTest API를 사용하여 로그인 후 여러 사이트 URL 속도 테스트 후 csv로 저장하는 코드

 

 ... 
import WebPageTest from "webpagetest";
import fs from "fs";
import { DateTime } from "luxon"; // Assuming you have luxon installed // npm install luxon

const wptServer = "https://www.webpagetest.org";
const wpt = new WebPageTest(wptServer, "8b3d67be-703f-4216-a6a2-1d74746c3e91");

const options = {
  pollResults: 5,
  firstViewOnly: true,
  location: "ec2-ap-northeast-2:Chrome",
  connectivity: "Native",
};

const generateScript = (url) => {
  return wpt.scriptToString([
    { logData: 0 },
    { navigate: "https://nid.naver.com/nidlogin.login" },
    { logData: 1 },
    { setCookie: ["https://nid.naver.com/nidlogin.login", "NNB=abcd"] },
    { setValue: ["name=name", "test@naver.com"] },
    { setValue: ["name=pw", "YOUR_PW"] },
    { click: "type=submit" },
    { navigate: url },
    "waitForComplete",
  ]);
};

const urls = [
    "https://section.blog.naver.com/",
  "https://mail.naver.com",
  // 나머지 URL들을 추가해주세요
];

const runTestForUrl = async (url) => {
  const script = generateScript(url);
  return new Promise((resolve, reject) => {
    wpt.runTest(script, options, (err, result) => {
      if (result) {
        resolve(result);
      } else {
        reject(err);
      }
    });
  });
};

const runTests = async () => {
  const finalResults = [];
  const timestamp = DateTime.local().toFormat("yyyyMMddHHmmss");
  const NNB = "abcd"; // You may change this value according to your requirement
  for (const url of urls) {
    try {
      const result = await runTestForUrl(url);
      if (result.data) {
        const median = result.data.median.firstView;
        finalResults.push({
          id: result.data.id,
          url: result.data.url,
          cls: median["chromeUserTiming.CumulativeLayoutShift"],
          lcp: median["chromeUserTiming.LargestContentfulPaint"],
          tbt: median["TotalBlockingTime"],
          fullyLoaded: median["fullyLoaded"]
        });
      }
    } catch (error) {
      console.error(error);
    }
  }
  const csvData = finalResults.map((result) => {
    return `${result.id},${result.url},${result.cls},${result.lcp},${result.tbt},${result.fullyLoaded}`;
  }).join("\n");

  const fileName = `test_${timestamp}_${NNB}.csv`;
  fs.writeFileSync(fileName, "id,url,cls,lcp,tbt,fullyLoaded\n" + csvData);
  console.log(`Results saved to ${fileName}`);
};

runTests();
"이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다."
Posted by 프리스케이터