Javascript:从Google的“我很幸运”功能获取重定向链接

时间:2018-12-16 10:31:24

标签: javascript google-apps-script

我需要编写一个Javascript函数,该函数采用Google的“我很幸运”按钮的重定向链接。

该功能应包含:

http://www.google.com/search?q="stackoverflow"&btnI

并返回:

https://stackoverflow.com

我尝试过:

function getRedirect(url) {
  var response = UrlFetchApp.fetch(url, {'followRedirects': true, 'muteHttpExceptions': true});
  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;
  }
}

但是它不起作用,因为它仅处理http重定向。我想Google的“幸运按钮”工作方式有所不同。

2 个答案:

答案 0 :(得分:1)

  • 您要从https://stackoverflow.com检索重定向链接的http://www.google.com/search?q="stackoverflow"&btnI的URL。

如果我的理解是正确的,那么该修改如何?

修改点:

  • 在这种情况下,请使用followRedirects: false
  • 您可以从标头和响应正文中检索URL。

修改后的脚本:

var url = 'http://www.google.com/search?q=%22stackoverflow%22&btnI';
var response = UrlFetchApp.fetch(url, {'followRedirects': false, 'muteHttpExceptions': true});
var redirectUrl = response.getHeaders()['Location'];
Logger.log(redirectUrl) // https://stackoverflow.com

您还可以按以下方式检索URL。

var redirectUrl = response.getContentText().match(/HREF=\"(\w.+)\"/)[1];
Logger.log(redirectUrl) // https://stackoverflow.com

注意:

  • 如果您使用http://www.google.com/search?q="stackoverflow"&btnI,请像http://www.google.com/search?q=%22stackoverflow%22&btnI那样进行URL编码。
    • 您也可以使用http://www.google.com/search?q=stackoverflow&btnI

参考:

如果我误解了你的问题,对不起。

答案 1 :(得分:-1)

如果您有权使用 php,那么您可以使用下面的代码。

我刚刚写了它并测试了它,此代码100%有效

<?php
$url = 'https://www.google.com/search?q=books&btnI';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$a = curl_exec($ch);
if(preg_match('#Location: (.*)#', $a, $r))
    $newUrl = trim($r[1]);
    $explode = explode('q=', $newUrl);
    print_r($explode[1]);
?>