对于我的 Node.Js 应用程序,我需要从.com
域中获取 Google 搜索结果的第一页,因为我需要"People also search for"
仅在 Google.Com 上显示的知识图信息。
我想我可以使用request
andcheerio
模块从 Google 的搜索结果页面中删除内容,但是当我尝试访问我需要的 URL 时,即https://www.google.com/search?gws_rd=ssl&site=&source=hp&q=google&oq=google
Google 会自动将我重定向到.de
域(因为我在德国)。
我尝试将其设置为首先加载http://www.google.com/ncr
url,该 url 会自动关闭浏览器中特定于国家/地区的重定向,但它不起作用......
有人知道我可以做些什么来让它发挥作用吗?
这是我的代码...谢谢!
var request = require("request");
var cheerio = require("cheerio");
function dataCookieToString(dataCookie) {
var t = "";
for (var x = 0; x < dataCookie.length; x++) {
t += ((t != "") ? "; " : "") + dataCookie[x].key + "=" + dataCookie[x].value;
}
return t;
}
function mkdataCookie(cookie) {
var t, j;
cookie = cookie.toString().replace(/,([^ ])/g, ",[12],$1").split(",[12],");
for (var x = 0; x < cookie.length; x++) {
cookie[x] = cookie[x].split("; ");
j = cookie[x][0].split("=");
t = {
key: j[0],
value: j[1]
};
for (var i = 1; i < cookie[x].length; i++) {
j = cookie[x][i].split("=");
t[j[0]] = j[1];
}
cookie[x] = t;
}
return cookie;
}
var dataCookie = mkdataCookie('MC_STORE_ID=66860; expires=' + new Date(new Date().getTime() + 86409000));
request({
uri: "https://www.google.com/ncr",
headers: {
'User-Agent': 'Mozilla/5.0',
"Cookie": dataCookieToString(dataCookie)
}
}, function(error, response, body) {
request({
uri: "https://www.google.com/search?gws_rd=ssl&site=&source=hp&q=google&oq=google",
headers: {
'User-Agent': 'Mozilla/5.0'
}
}, function(error, response, body) {
console.log(body);
var $ = cheerio.load(body);
$(".kno-fb-ctx").each(function() {
var link = $(this);
var text = link.text();
console.log(text);
});
});
});