问题描述
我正在尝试获取特定网站最终目的地的 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”中。
结果:
使用 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 时,它可能无法使用。所以请注意这一点。