反向缩短 URL 以获得原始 URL 在缩短 Google 工作表之前

Reverse Shortened URL to Get the Original URL Before the Shortening in Google Sheets

我有一个 sheet,我根据搜索查询收集带有链接的推文。然而,Twitter 为每条推文提供了简短的 URL 格式 (t.co),而不是共享的原始 URL。

有没有办法使用公式或google代码来回溯短url并获取最终目的地URL?推文作者分享的原件?

     What i have        |       what i'm looking for
---------------------------------------------------------------------------
https://t​.co/dura1sUSxm | https://www.jpost.com/Breaking-News/Russia-Saudi-Arabia-plan-deals-for-2-bln-for-Putins-visit-to-Riyadh-604200
https://t​.co/Ayy7ww8dFX | https://www.washingtonpost.com/national-security/trump-says-little-as-his-gop-allies-condemn-turkeys-incursion-into-syria/2019/10/09/c46210f6-eaab-11e9-9306-47cb0324fd44_story.html
https://t​.co/WLj6PipXkC | https://www.newsweek.com/teacher-fired-refusing-sign-pro-document-1262083
https://t​.co/UoqiqfaHup | https://www.reuters.com/article/us-environment-waste-idUSKBN1WP1RE
https://t​.co/hO9swbmeeZ | https://www.washingtonpost.com/national-security/trump-says-little-as-his-gop-allies-condemn-turkeys-incursion-into-syria/2019/10/09/c46210f6-eaab-11e9-9306-47cb0324fd44_story.html
https://t​.co/Ve8ZpCp1s1 | https://www.reuters.com/article/us-environment-waste-idUSKBN1WP1RE

答案:

是的,这可以使用 UrlFetchAppfetch 方法,收集 headers 并读取 Location 属性 .

方法:

您可以使用 UrlFetchApp 获取包含最终 URL 端点的目的地的 headers。然而,将它放在一个循环中很重要,因为有时多个 URL 缩短服务串联在一起,因此您可能无法在一次获取后到达目的地 URL。

代码:

function getLocation(url) {
  var fetched = UrlFetchApp.fetch(url, {
    followRedirects: false
  })

  if (fetched.getHeaders().Location !== undefined) {
    return getLocation(fetched.getHeaders().Location)
  }
  return url
}