2013-11-26 67 views
0

有没有人使用Node Cheerio刮擦整个网站,而不仅仅是刮板指向的home/first page?Node Cheerio刮去整个网站

在这一刻我正在做的只是刮目标网页。

request('http://arandomsite.com/', function (error, response, html) { 
    if (!error && response.statusCode == 200){ 
     var $ = cheerio.load(html); 
      ... 
      ... 
      ... 
}; 

回答

1

我从来没有使用Cheerio,但我会假设(如可能与其他刮板),它只会做你指向它的页面。假设cheerio.load返回类似API jQuery的,你可能会不得不做一些像

$('a').each(function(index, a) { 
    //TODO: You may want to keep track here of which you have done, and not redo any. 
    request('http://arandomsite.com' + a.attr('href'), myPageProcessFunction); 
}); 

很明显,你将需要添加的东西像I帧以及确保你得到一个完整的结果。

为了澄清,这里是一些更新的代码:

request('http://arandomsite.com/', function responseFunction(error, response, html) { 
if (!error && response.statusCode == 200){ 
    var $ = cheerio.load(html); 
    $('a').each(function(index, a) { 
     request('http://arandomsite.com' + a.attr('href'), responseFunction); 
    }); 
}; 
}); 
+0

与此唯一的问题是请求的功能是直接低于我的节点相关性的变量,因此一个问题,我可以看到的是,通过包装$('a')。each(function(index,a){};'中的请求会导致$是未定义的 – leaksterrr

+1

我不是说要包装请求,这段代码应该在$当我说每个链接上的呼叫请求,我的意思是做一个新的请求调用,并传递当前函数作为回调结果。 –

+0

我看到你的逻辑和感谢更新的代码,这是有道理的。唯一的问题我没有那个它是说a没有方法'attr'?这是一个链接到一个完整的代码,以让您更好地了解我在做什么http://pastie.org/private/snykxn92q23ga8srnpak3a#1 – leaksterrr