【问题标题】:How to pull data from YouTube API to a Google Sheet with Channel Links如何使用频道链接将数据从 YouTube API 提取到 Google 表格
【发布时间】:2022-09-25 05:50:00
【问题描述】:

我是这里的新手。我尝试了许多脚本来执行以下操作。 (显然来自stackoverflow中的其他问题 - 我还不太擅长编写代码)

我的目标是,

  1. 从工作表 1 A2:A 的通道链接中读取通道 ID
  2. 将订阅者总数拉到 B2:B
  3. 将频道总观看次数统计到 C2:C
  4. 将视频上传总数拉到 D2:D

    我已经有了 API 密钥,并尝试了我所能做的几乎所有事情来实现这一点。但是,我无法让它工作。

    有人可以教育我如何使这项工作吗?

    我会非常感谢你的帮助。提前感谢<3

  • 这些信息是否可以使用 apikey 公开?请编辑您的问题,包括minimal reproducible example 并描述我无法让它工作。有错误吗?数据没有回来吗?
  • 请提供足够的代码,以便其他人可以更好地理解或重现该问题。

标签: youtube-api youtube-data-api


【解决方案1】:

这是一个在Google Sheet 上执行所描述技巧的 Google Apps 脚本:

// This Google Apps Script fills a Google Sheet with statistics associated to given YouTube channels.

// More precisely this script assumes that in columns A after the first row there are channel identifiers,
// which can be a channel ID (such as `UC0aMPje3ZACnQPKM_qzY0vw`) or any channel URL such as:
// - https://www.youtube.com/channel/UCK_cUZLMpibyRiIdp0uF-lQ
// - https://www.youtube.com/user/Fairphone
// - https://www.youtube.com/c/lemondefr

function fills_statistics_associated_to_given_youtube_channels() {
  const A = 1, B = 2, C = 3, D = 4;
  var sheet = SpreadsheetApp.getActiveSheet();
  const YOUTUBE_CHANNELS = YouTube.Channels;
  const CHANNEL_URL_PREFIX = "https://www.youtube.com/";
  // Consider an arbitrary number of channels written after the first row.
  for(var row = 2; row <= sheet.getLastRow(); row++)
  {
    const channelURL = sheet.getRange(row, A).getValue().toString().replace(CHANNEL_URL_PREFIX, "");
    // Retrieve the channel ID from the channel identifier provided.
    // If the channel URL provided is an username-based one, obtain the associated channel ID.
    var channelID;
    if(channelURL.startsWith("user/"))
      channelID = YOUTUBE_CHANNELS.list("id", {"forUsername": channelURL.replace("user/", "")}).items[0].id;
    // As YouTube Data API v3 Channels: list `forUsername` filter doesn't work for this kind of URL, proceed with a YouTube UI reverse-engineering approach.
    // This approach consists in obtaining JSON encoded JavaScript `ytInitialData` from the HTML code of the YouTube UI channel.
    else if(channelURL.startsWith("c/"))
    {
      // Note that the following reverse-engineering method isn't working currently because of escaped JSON syntax and I haven't found any clean way to parse it correctly.
      /*
      const channelHTML = UrlFetchApp.fetch(CHANNEL_URL_PREFIX + channelURL).getContentText();
      const ytInitialDataStr = channelHTML.split('">var ytInitialData = ', 2)[1].split(";</script>", 1)[0];
      const ytInitialDataJSON = JSON.parse(ytInitialDataStr);
      channelID = ytInitialDataJSON["responseContext"]["serviceTrackingParams"][0]["params"][6]["value"];
      continue;
      */

      // However by relying on a YouTube operational API instance doing this reverse-engineering method, it works fine. Nevertheless if YouTube servers detect the instance as suspicious, you have to host your own instance cf below. If you go this way, replace `yt.lemnoslife.com` to your instance hostname.
      // YouTube operational API source code is available at: https://github.com/Benjamin-Loison/YouTube-operational-API
      const channelStr = UrlFetchApp.fetch("https://yt.lemnoslife.com/channels?part=snippet&forUsername=" + channelURL.replace("c/", "")).getContentText();
      const channelJSON = JSON.parse(channelStr);
      channelID = channelJSON["items"][0]["id"];
    }
    // Not filtering with `if(channelURL.startsWith("channel/"))` in order to support channel ID too.
    else
      channelID = channelURL.replace("channel/", "");
    // For more details see YouTube Data API v3 Channels: list endpoint documentation: https://developers.google.com/youtube/v3/docs/channels/list
    // Note that the channel ID retrieval can't be optimized in terms of HTTPS requests.
    // However could optimize the other HTTPS requests to YouTube Data API v3 by implementing using `id` filter to provide up to 50 channel IDs as documented by `maxResults`.
    const statistics = YOUTUBE_CHANNELS.list("statistics", {"id": channelID}).items[0].statistics;
    sheet.getRange(row, B).setValue(statistics.subscriberCount);
    sheet.getRange(row, C).setValue(statistics.viewCount);
    sheet.getRange(row, D).setValue(statistics.videoCount);
  }
}

【讨论】:

  • 非常感谢代码。正如我看到的代码不能在具有“c”的链接上工作,有没有办法通过只提供这样的频道 ID (docs.google.com/spreadsheets/d/…) 来使其工作?
  • @Bookus 在您的 Google 表格中,Fairphone 和 lemondefr 都不起作用,因为它们是 c/ 还是 user/ 网址存在歧义(因为它对 forUsername 很重要)。但是,只需提供频道 ID(例如 UCK_cUZLMpibyRiIdp0uF-lQ)或基于频道 ID 的 URL(例如 youtube.com/channel/UCK_cUZLMpibyRiIdp0uF-lQ)即可。
  • 感谢您澄清...如果是这种情况,我想知道如何提取其中包含“c/”的频道 URL 的数据。如果您有任何解决方法,请提出建议。 TIA <3
  • I updated my answer。请注意,当前 YouTube 服务器检测到官方 YouTube 操作 API 实例 (yt.lemnoslife.com) as suspicious,因此您必须 host your own instance 才能使更新的脚本正常工作。
【解决方案2】:

尝试这个

function myFunction() {

  let sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  let range = sheet.getRange(2,1, sheet.getLastRow()-1);
  let values = range.getValues();
  let mapValues = values.map(function(sr){return sr[0];}).join(",");
  let results = YouTube.Channels.list("statistics, contentDetails",{id: mapValues});
  let modifyResults = results.items.map(function(sr){return [sr.statistics.subscriberCount, sr.statistics.videoCount, sr.statistics.viewCount]});

  sheet.getRange(2,2, modifyResults.length,modifyResults[0].length).setValues(modifyResults);
    
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    相关资源
    最近更新 更多