【问题标题】:Return link to redirect url返回链接以重定向 url
【发布时间】:2021-02-19 04:13:31
【问题描述】:

我正在尝试获取特定网站的最终目的地的 url,但我发现在我的电子表格中用作函数的所有模板都只返回初始链接:

https://stackoverflow.com/a/50733029

function getRedirect(url) {
  var response = UrlFetchApp.fetch(url, {'followRedirects': false, 'muteHttpExceptions': false});
  var redirectUrl = response.getHeaders()['Location']; // undefined if no redirect, so...
  var responseCode = response.getResponseCode();
  if (redirectUrl) {                                   // ...if redirected...
    var nextRedirectUrl = getRedirect(redirectUrl);    // ...it calls itself recursively...
    Logger.log(url + " is redirecting to " + redirectUrl + ". (" + responseCode + ")");
    return nextRedirectUrl;
  }
  else {                                               // ...until it's not
    Logger.log(url + " is canonical. (" + responseCode + ")");
    return url;
  }
} 

这是我放的模型:
=getRedirect("https://c.newsnow.co.uk/A/1067471289?-833:12")

在电子表格中返回:
https://c.newsnow.co.uk/A/1067471289?-833:12

我想收集重定向后的链接:
https://sports.ndtv.com/football/europa-league-bruno-fernandes-double-helps-manchester-united-thrash-real-sociedad-gareth-bale-stars-for-tottenham-2373767

【问题讨论】:

    标签: google-apps-script redirect google-sheets google-sheets-formula urlfetch


    【解决方案1】:

    当我看到 URL https://c.newsnow.co.uk/A/1067471289?-833:12 的 HTML 时,我认为在这种情况下,https://sports.ndtv.com/football/europa-league-bruno-fernandes-double-helps-manchester-united-thrash-real-sociedad-gareth-bale-stars-for-tottenham-2373767 的值可能可以使用 IMPORTXML 和 xpath 直接检索。示例公式如下。

    示例公式:

    =IMPORTXML(A1,"//a/@href")
    
    • 在这种情况下,请将https://c.newsnow.co.uk/A/1067471289?-833:12的URL放到单元格“A1”中。

    结果:

    使用 Google Apps 脚本:

    当您想使用 Google Apps 脚本时,您还可以使用以下脚本。在这种情况下,请将=SAMPLE("https://c.newsnow.co.uk/A/1067471289?-833:12") 的自定义公式放入单元格中。

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

    注意:

    • 在此示例公式中,xpath 用于https://c.newsnow.co.uk/A/1067471289?-833:12 的 URL。因此,当您将其用于其他 URL 时,它可能无法使用。所以请注意这一点。

    参考:

    【讨论】:

      猜你喜欢
      • 2017-02-02
      • 1970-01-01
      • 2013-08-03
      • 1970-01-01
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      • 2021-04-16
      • 1970-01-01
      相关资源
      最近更新 更多