使用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 */ }); }); } }); 

但我不能弄清楚如何调用它自己一旦它刮了根页面,或填充一个数组或url,它需要刮。

然后是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(); 

这需要一个位置的数组,但是再一次,一旦你开始一个数组,你不能添加更多的位置去遍历所有的产品页面。

而我甚至不能得到杏工作,出于某种原因,我得到一个错误。

那么,我如何修改上面的任何一个示例(或者上面没有列出的任何东西)来刮一个网站,find所有的产品页面,在那里find一些数据(jquery.someclass示例应该做的伎俩),并保存一个数据库?

谢谢!

就个人而言,我使用节点IO来刮一些网站。 https://github.com/chriso/node.io

更多关于抓取的细节可以在wiki中find!


我用Casperjs取得了相当不错的成功。 这是一个build立在Phantomjs之上的相当好的库。 我喜欢它,因为它相当简洁。 callback函数可以像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); }; 

然后,您可以使用节点fs(或其他任何您想要的)将数据推送到XML,CSV或任何您想要的内容。 当我build立我的刮刀时,抓取BBC照片的例子非常有帮助。

这是万宝盛华可以做到的一个观点。 它有一个非常有力和广泛的API。 我挖它,以防万一你不能说:)。

我的完整刮板示例是: https : //gist.github.com/imjared/5201405 。