nodejs抓取网页

nodejs使用http.request抓取网页。option中还可以设置其他参数,例如timeout: 50000。即请求超时的时间。也可以加一些自定义的参数,比如加一个tryTime: 3, 当请求出错后,在回调中tryTime--,如果>=0 那么回调中再次的调用一次spider。

回调函数示例

function callback(data, opt, encode) {
    if (data == null && opt.tryTimes-- > 0) {
        console.log('path ' + opt.path + ' error, try again');
        spider(opt, encode, callback);
        return;
    }
    if (data == null) {
        console.log(opt.path + 'fail!');
        return;
    }
    // process the data here
}

spider模块如下

var http = require('http');
/**
var options =
{
host: 'blog.discussquiz.com',
port: 80,
path: '/article/1',
method: 'GET'
};
*/
function spiderUrl(opt, encode, fnSpiderData) {
    var req = http.request(opt, function(res) {
        res.setEncoding(encode);
        var g_data='';
        res.on('data', function (chunk) {
            g_data += chunk;
        });
        res.on('end', function() {
            fnSpiderData(g_data, opt, encode);
        });
    });
    req.on('error', function(e) {
        console.log('problem with request ' + opt.path + ' : ' + e.message);
        fnSpiderData(null, opt, encode);
    });
    req.end();
}
module.exports = spiderUrl;
留言:
onatkh 说:
2015/11/19 13:41:56

非常不错的博客,看着非常清楚,且实用。

龙门外的鱼 回复: onatkh
2015/11/28 4:20:37

嗯哼嗯哼,好久没更新了,一直在玩。。。