4

对于我的 Node.Js 应用程序,我需要从.com域中获取 Google 搜索结果的第一页,因为我需要"People also search for"仅在 Google.Com 上显示的知识图信息。

我想我可以使用requestandcheerio模块从 Google 的搜索结果页面中删除内容,但是当我尝试访问我需要的 URL 时,即https://www.google.com/search?gws_rd=ssl&site=&source=hp&q=google&oq=googleGoogle 会自动将我重定向到.de域(因为我在德国)。

我尝试将其设置为首先加载http://www.google.com/ncrurl,该 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);
        });
    });
});
4

1 回答 1

3

这是解决方案:它比我想象的要容易得多。

但是,我仍然有一个问题,即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);
        });
    });
});
于 2015-01-02T02:34:09.137 回答