对于我的 Node.Js 应用程序,我需要从 .com
域获取 Google 搜索结果的第一页,因为我需要 “People also search for”
知识图谱信息,仅显示在 Google.Com 上。
我想我可以使用 request
和 cheerio
模块从 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);
});
});
});
最佳答案
这是解决方案:它比我想象的要容易得多。
但是,我仍然有一个问题,即我得到的 body
不包含仅在启用 javascript 时才会显示的内容。
有人知道如何修改下面的代码,以便它也将启用 javascript 的内容包含到正文中吗?
var request = require('request');
var cheerio = require("cheerio");
request = request.defaults({jar: true});
var options = {
url: 'http://www.google.com/ncr',
headers: {
'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16'
}
};
request(options, function () {
request('https://www.google.com/search?gws_rd=ssl&site=&source=hp&q=google&oq=google', function (error, response, body) {
var $ = cheerio.load(body);
$("li").each(function() {
var link = $(this);
var text = link.text();
console.log(text);
});
});
});
关于javascript - 使用 Node.Js 中的请求从 Google 搜索结果中抓取内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27735919/