微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

返回重定向 url 的链接 示例公式:结果:使用 Google Apps 脚本:注意:参考:

如何解决返回重定向 url 的链接 示例公式:结果:使用 Google Apps 脚本:注意:参考:

我正在尝试获取特定网站最终目的地的 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

解决方法

当我看到 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”中。

结果:

enter image description here

使用 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 时,它可能无法使用。所以请注意这一点。

参考:

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。