我需要编写一个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的“幸运按钮”工作方式有所不同。
答案 0 :(得分:1)
https://stackoverflow.com
检索重定向链接的http://www.google.com/search?q="stackoverflow"&btnI
的URL。如果我的理解是正确的,那么该修改如何?
followRedirects: false
。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]);
?>