YouTube 数据分析服务

借助 YouTube 数据分析服务,您可以在 Apps 脚本中使用 YouTube Analytics API。此 API 可让用户检索 YouTube 视频和频道的观看统计信息、热门程度指标以及受众特征信息。

参考

如需详细了解此服务,请参阅 YouTube Analytics API 的参考文档。与 Apps 脚本中的所有高级服务一样,YouTube 数据分析服务使用的对象、方法和参数与公共 API 相同。如需了解详情,请参阅如何确定方法签名

示例代码

以下示例代码使用了 YouTube Analytics API 第 2 版YouTube Data API 第 3 版(您可以通过 Apps 脚本中的 YouTube 服务进行访问)。

如需报告问题和寻求其他支持,请参阅 YouTube API 支持指南

创建报告

此函数会创建一个电子表格,其中包含频道视频的每日观看次数、观看时长指标和新订阅者人数。

advanced/youtubeAnalytics.gs
/**
 * Creates a spreadsheet containing daily view counts, watch-time metrics,
 * and new-subscriber counts for a channel's videos.
 */
function createReport() {
  // Retrieve info about the user's YouTube channel.
  const channels = YouTube.Channels.list('id,contentDetails', {
    mine: true
  });
  const channelId = channels.items[0].id;

  // Retrieve analytics report for the channel.
  const oneMonthInMillis = 1000 * 60 * 60 * 24 * 30;
  const today = new Date();
  const lastMonth = new Date(today.getTime() - oneMonthInMillis);

  const metrics = [
    'views',
    'estimatedMinutesWatched',
    'averageViewDuration',
    'subscribersGained'
  ];
  const result = YouTubeAnalytics.Reports.query({
    ids: 'channel==' + channelId,
    startDate: formatDateString(lastMonth),
    endDate: formatDateString(today),
    metrics: metrics.join(','),
    dimensions: 'day',
    sort: 'day'
  });

  if (!result.rows) {
    console.log('No rows returned.');
    return;
  }
  const spreadsheet = SpreadsheetApp.create('YouTube Analytics Report');
  const sheet = spreadsheet.getActiveSheet();

  // Append the headers.
  const headers = result.columnHeaders.map((columnHeader)=> {
    return formatColumnName(columnHeader.name);
  });
  sheet.appendRow(headers);

  // Append the results.
  sheet.getRange(2, 1, result.rows.length, headers.length)
      .setValues(result.rows);

  console.log('Report spreadsheet created: %s',
      spreadsheet.getUrl());
}

/**
 * Converts a Date object into a YYYY-MM-DD string.
 * @param {Date} date The date to convert to a string.
 * @return {string} The formatted date.
 */
function formatDateString(date) {
  return Utilities.formatDate(date, Session.getScriptTimeZone(), 'yyyy-MM-dd');
}

/**
 * Formats a column name into a more human-friendly name.
 * @param {string} columnName The unprocessed name of the column.
 * @return {string} The formatted column name.
 * @example "averageViewPercentage" becomes "Average View Percentage".
 */
function formatColumnName(columnName) {
  let name = columnName.replace(/([a-z])([A-Z])/g, '$1 $2');
  name = name.slice(0, 1).toUpperCase() + name.slice(1);
  return name;
}