我的 PageSpeed Appscript 代码有什么问题?

Whats wrong with my PageSpeed Appscript code?

提问人:Brandon 提问时间:7/19/2023 最后编辑:Brandon 更新时间:7/19/2023 访问量:28

问:

我的脚本曾经工作过,现在它可以提取任何数据。一段时间以来,我一直在尝试解决代码,但不断出现不同的错误,所以我想我会在这里发布它。

该脚本允许从 Google 的 PSI 中提取字段数据以获取网址列表。该脚本每ONE_HOUR运行一次 - 但我似乎无法让它提取数据。这是我的代码(减去我的 API 密钥和 URL 列表):

这是我面临的错误以及脚本应该导出的内容的两张图像

错误消息图像

数据导出图像

任何帮助将不胜感激!

var pageSpeedApiKey = 'Enter API key';

const URL_COLUMN_INDEX = 1;
const DATE_COLUMN_INDEX = 0;

const ONE_HOUR = 60 * 60 * 1000;
const CHECK_FREQUENCY = ONE_HOUR * 24;

const HEADERS = ["Timestamp", "URL", "Device", "Performance Score", "FCP", "LCP", "CLS", "Interactive", "Total Blocking Time", "Speed Index", "First Input Delay (FID)"];

const urls = [
  'enter URL',

];

var spreadsheet = SpreadsheetApp.openById('sheetURL');
var sheet = spreadsheet.getSheetByName('results');

let lastRow = sheet.getLastRow();
let maxLookback = urls.length * 3;
let startingRow = lastRow - maxLookback + 1;
let lastUrlsAndDates = sheet.getRange(startingRow, 1, maxLookback, 2).getValues();

function createHeaders() {
  sheet.getRange(1, 1, 1, HEADERS[0].length).setValues(HEADERS);
}

function monitor() {
  console.info("Checking " + urls.length + " URLs...");
  for (var i = 0; i < urls.length; i++) {
    let url = urls[i];
    if (!isAlreadyChecked(url)) {
      checkPerformances(url);
      break;
    }
  }
  console.info("Nothing more to do...");
}

function checkPerformances(url) {
  populatePageSpeedInfo(url, 'desktop');
  populatePageSpeedInfo(url, 'mobile');
}

function populatePageSpeedInfo(urlToMonitor, strategy) {
  console.info("Getting page speed info for: " + urlToMonitor + " With Strategy: " + strategy);
  var rowNumber = reserveRowForUrl(urlToMonitor, strategy);
  var pageSpeedUrl = 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=' + urlToMonitor + '&key=' + pageSpeedApiKey + '&strategy=' + strategy;
  var response = UrlFetchApp.fetch(pageSpeedUrl, { muteHttpExceptions: true });
  if (response.getResponseCode() == 200) {
    var json = JSON.parse(response.getContentText());
    instertDataToSheet(rowNumber, urlToMonitor, json, strategy);
  } else {
    sheet.deleteRow(rowNumber);
    console.error("Unable to check performances for: '" + urlToMonitor + "' Error: " + response.getResponseCode());
  }
}

function isAlreadyChecked(url) {
  let lastCheckDate = getLastCheckTime(url);
  let elapsedSinceLastCheck = new Date() - lastCheckDate;
  return elapsedSinceLastCheck < CHECK_FREQUENCY;
}

function getLastCheckTime(url) {
  for (var i = lastUrlsAndDates.length - 1; i > 0; i--) {
    let curUrl = lastUrlsAndDates[i][URL_COLUMN_INDEX];
    if (curUrl === url) {
      return new Date(lastUrlsAndDates[i][DATE_COLUMN_INDEX]);
    }
  }
  return new Date(0);
}

function reserveRowForUrl(urlToMonitor, strategy) {
  var lock = LockService.getDocumentLock();
  try {
    lock.tryLock(10000);
    var lastRow = sheet.getLastRow();
    var rowNumber = lastRow + 1;
    sheet.insertRowBefore(rowNumber);
    sheet.getRange(rowNumber, DATE_COLUMN_INDEX + 1).setValue(new Date());
    sheet.getRange(rowNumber, URL_COLUMN_INDEX + 1).setValue(urlToMonitor);
    sheet.getRange(rowNumber, URL_COLUMN_INDEX + 2).setValue(strategy);
    return rowNumber;
  } finally {
    lock.releaseLock();
  }
}

function instertDataToSheet(rowNumber, urlToMonitor, json, strategy) {
  var metrics = json.lighthouseResult.categories.performance.auditRefs;
  var metricData = metrics.reduce(function (data, metric) {
    if (metric.result && metric.result.numericValue) {
      data[metric.id] = metric.result.numericValue;
    }
    return data;
  }, {});

  var values = [
    new Date(),
    urlToMonitor,
    strategy,
    metricData['performance-score'] || '',
    metricData['first-contentful-paint'] || '',
    metricData['largest-contentful-paint'] || '',
    metricData['cumulative-layout-shift'] || '',
    metricData['interactive'] || '',
    metricData['total-blocking-time'] || '',
    metricData['speed-index'] || '',
    metricData['max-potential-fid'] || ''
  ];
  sheet.getRange(rowNumber, 4, 1, HEADERS[11].length).setValues([values]);
}

function onOpen(e) {
  var menu = SpreadsheetApp.getUi().createMenu('Page Speed Insights');
  menu.addItem('Create Headers', 'createHeaders');
  menu.addItem('Monitor', 'monitor');
  menu.addToUi();
}```
PageSpeed 谷歌-PageSpeed-Insights-API py-appscript

评论


答: 暂无答案