Google Analytics应用脚本获取包含特定字词的所有媒体事件标签



我正在尝试编写一个脚本,其中包含仅与媒体相关的所有事件类别,我希望evenLabels仅包含标题中包含"顶空"一词的媒体标题。 我有一个脚本,但我的结果完全错误,我不确定我应该更改什么来纠正它。

脚本为:

function runDemo() {
  try {
    var firstProfile = getFirstProfile();
    var results = getReportDataForProfile(firstProfile);
    outputToSpreadsheet(results);
  } catch(error) {
    Browser.msgBox(error.message);
  }
}
function getFirstProfile() {
  var accounts = Analytics.Management.Accounts.list();
  if (accounts.getItems()) {
    var firstAccountId = accounts.getItems()[0].getId();
    var webProperties = Analytics.Management.Webproperties.list(firstAccountId);
    if (webProperties.getItems()) {
      var firstWebPropertyId = webProperties.getItems()[0].getId();
      var profiles = Analytics.Management.Profiles.list(firstAccountId, firstWebPropertyId);
      if (profiles.getItems()) {
        var firstProfile = profiles.getItems()[0];
        return firstProfile;
      } else {
        throw new Error('No views (profiles) found.');
      }
    } else {
      throw new Error('No webproperties found.');
    }
  } else {
    throw new Error('No accounts found.');
  }
}
function getReportDataForProfile(firstProfile) {
  var profileId = firstProfile.getId();
  var tableId = 'ga:' + profileId;
  var startDate = getLastNdays(14);   // 2 weeks (a fortnight) ago.
  var endDate = getLastNdays(0);      // Today.
  var optArgs = {
    'dimensions': 'ga:eventLabel' ,             // Comma separated list of dimensions
    'filters': 'ga:eventLabel=~headspace',   // Display only google traffic                
  };

  // Make a request to the API.
  var results = Analytics.Data.Ga.get(
      tableId,                    // Table id (format ga:xxxxxx).
      startDate,                  // Start-date (format yyyy-MM-dd).
      endDate,                    // End-date (format yyyy-MM-dd).
     'ga:totalEvents', // Comma seperated list of metrics.
      optArgs);
  if (results.getRows()) {
    return results;
  } else {
    throw new Error('No views (profiles) found');
  }
}
function getLastNdays(nDaysAgo) {
  var today = new Date();
  var before = new Date();
  before.setDate(today.getDate() - nDaysAgo);
  return Utilities.formatDate(before, 'GMT', 'yyyy-MM-dd');
}
function outputToSpreadsheet(results) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet();
  // Print the headers.
  var headerNames = [];
  for (var i = 0, header; header = results.getColumnHeaders()[i]; ++i) {
    headerNames.push(header.getName());
  }
  sheet.getRange(1, 1, 1, headerNames.length)
      .setValues([headerNames]);
  // Print the rows of data.
  sheet.getRange(2, 1, results.getRows().length, headerNames.length)
      .setValues(results.getRows());
}

我建议在Google Sheets中使用Google Analytics插件。https://chrome.google.com/webstore/detail/google-analytics/fefimfimnhjjkomigakinmjileehfopp?hl=en

这将允许您访问所有Google Analytics数据,而无需编写代码。然后,如果您需要进一步操作数据,则可以移回Google Apps Script。

最新更新