首页 > 解决方案 > 在 Google 表格上使用 JSON 获取 URL

问题描述

我正在尝试使用 JSON 来提取 Spotify 播放列表上的关注者。似乎各种播放列表具有不同的 HTML 数据 - 这使得它变得复杂。

这是我目前在 Google Apps Scripts 中的代码。(@Tanaike 提供)

function SAMPLE(url) {
  const res = UrlFetchApp.fetch(url).getContentText();
  const v = res.replace(/&/g, "&").match(/Spotify\.Entity \=([\s\S\w]+?);/);
  return v && v.length == 2 ? JSON.parse(v[1].trim()).followers.total : "Value cannot be 
retrieved.";
}

然后我只是在单元格中使用了 =SAMPLE(the link)

但是,我在某些播放列表链接上收到此错误(我不知道为什么): SyntaxError: Unexpected end of JSON input(第 4 行)。

工作链接示例: https ://open.spotify.com/playlist/5aSO2lT7sVPKut6F9L6IAc https://open.spotify.com/playlist/7qvQVDnLe4asawpZqYhKMQ

无效链接示例(显示上述错误) https://open.spotify.com/playlist/2Um96ZbAH1fFTHmAcpO50n https://open.spotify.com/playlist/68jtRFcWtaFNHKO5wYLBsk

大约 80% 的链接有效(我有超过 400 个)。任何指导或帮助将不胜感激。

谢谢大家!

标签: jsongoogle-apps-scriptgoogle-sheets

解决方案


我相信你的目标如下。

  • 您想从以下 URL 检索关注者的数量。

      https://open.spotify.com/playlist/5aSO2lT7sVPKut6F9L6IAc
      https://open.spotify.com/playlist/7qvQVDnLe4asawpZqYhKMQ
      https://open.spotify.com/playlist/2Um96ZbAH1fFTHmAcpO50n
      https://open.spotify.com/playlist/68jtRFcWtaFNHKO5wYLBsk
      https://open.spotify.com/playlist/2phIYXF2hAd5gTj00IwXbU
      https://open.spotify.com/playlist/7MBKSFzpPLQ9ryPtydXVwf
      https://open.spotify.com/playlist/148My4xA7WoEaNDmnl2A8Z
      https://open.spotify.com/playlist/4zMaYNXz2pP1OPGz9SIJhX
      https://open.spotify.com/playlist/2hBohCkXzjzTLh6jtd7gUZ
    

修改点:

  • 我认为在当前阶段,检索所有JSON数据并解析数据,然后检索值。在这种情况下,我认为可能包含特定字符并且这些字符可能会出现问题。

所以在这个答案中,我想从 JSON 数据中检索值的一部分并解析它并返回值。修改后的脚本如下。

修改后的脚本:

function SAMPLE(url) {
  const res = UrlFetchApp.fetch(url).getContentText();
  const v = res.match(/followers":({[\s\S\w]+?})/);
  return v && v.length == 2 ? JSON.parse(v[1].trim()).total : "Value cannot be retrieved.";
}

结果:

当上述脚本用于上述 9 个 URL 时,会得到以下结果。

在此处输入图像描述

笔记:

  • 此示例脚本适用于您问题中的 URL。因此,当您针对其他 URL 进行测试时,该脚本可能无法使用。而且,当服务器端的 HTML 结构发生变化时,脚本可能无法使用。所以请注意这一点。

2022 年 1 月 15 日更新:

似乎 HTML 数据的规范有点变化。所以我更新了上面的脚本如下。

示例脚本:

function SAMPLE(url) {
  const res = UrlFetchApp.fetch(url).getContentText();
  const v = res.match(/"followers":({[\s\S\w]+?})/);
  return v && v.length == 2 ? JSON.parse(v[1].trim()).total : "Value cannot be retrieved.";
}

推荐阅读