使用Node.js进行爬网

R0b*_*n1k 11 node.js

完成Node.js noob,所以不要判断我......

我有一个简单的要求.抓取网站,查找所有产品页面,并从产品页面保存一些数据.

更简单的说完了.

看看Node.js样本,我找不到类似的东西.

请求刮刀:

request({uri:'http://www.google.com'}, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    var window = jsdom.jsdom(body).createWindow();
    jsdom.jQueryify(window, 'path/to/jquery.js', function (window, jquery) {
      // jQuery is now loaded on the jsdom window created from 'body'
      jQuery('.someClass').each(function () { /* Your custom logic */ });
    });
  }
});
Run Code Online (Sandbox Code Playgroud)

但是我无法弄清楚如何在刮擦根页面时调用它,或者填充它需要刮掉的数组或网址.

然后是http代理方式:

var agent = httpAgent.create('www.google.com', ['finance', 'news', 'images']);

agent.addListener('next', function (err, agent) {
  var window = jsdom.jsdom(agent.body).createWindow();
  jsdom.jQueryify(window, 'path/to/jquery.js', function (window, jquery) {
    // jQuery is now loaded on the jsdom window created from 'agent.body'
    jquery('.someClass').each(function () { /* Your Custom Logic */ });

    agent.next();
  });
});

agent.addListener('stop', function (agent) {
  sys.puts('the agent has stopped');
});

agent.start();
Run Code Online (Sandbox Code Playgroud)

这需要一系列的位置,但是再一次,一旦你开始使用数组,你就无法为它添加更多的位置来浏览所有的产品页面.

我甚至无法让Apricot工作,出于某种原因我得到了一个错误.

那么,我如何修改以上任何示例(或上面未列出的任何内容)来刮取网站,找到所有产品页面,在那里找到一些数据(jquery.someclass示例应该可以做到这一点)并将其保存到一个db?

谢谢!

San*_*nda 12

就个人而言,我使用Node IO来抓取一些网站.https://github.com/chriso/node.io

有关抓取的更多细节可以在维基中找到!



imj*_*red 8

我已经用Casperjs抓住了很好的成功.这是一个非常漂亮的图书馆,建立在Phantomjs之上.我喜欢它,因为它相当简洁.回调可以作为foo.then()执行,这是非常简单易懂的,我甚至可以使用jQuery,因为Phantomjs是webkit的一个实现.例如,以下内容将实例化Casper的实例,并将存档页面上的所有链接推送到名为"links"的数组.

var casper = require("casper").create();

var numberOfLinks = 0;
var currentLink = 0;
var links = [];
var buildPage, capture, selectLink, grabContent, writeContent;

casper.start("http://www.yoursitehere.com/page_to/scrape/", function() {
    numberOfLinks = this.evaluate(function() {
        return __utils__.findAll('.nav-selector a').length;
    });
    this.echo(numberOfLinks + " items found");

    // cause jquery makes it easier
    casper.page.injectJs('/PATH/TO/jquery.js');
});


// Capture links
capture = function() {
    links = this.evaluate(function() {
        var link = [];
        jQuery('.nav-selector a').each(function() {
            link.push($(this).attr('href'));
        });
        return link;
    });
    this.then(selectLink);
};
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用节点fs(或其他任何您想要的东西)将数据推送到XML,CSV或任何您想要的内容.当我制作刮刀时,刮BBC照片例子非常有用.

这是一个10,000英尺的casper可以做的视图.它有一个非常强大和广泛的API.我挖了它,万一你不知道:).

我的完整拼写示例如下:https://gist.github.com/imjared/5201405.