使用npm爬虫爬取链接时,出现错误:
C:\Users\ryani\Desktop\JavaScript\crawler\crawler.js:15
$('a').each(function(index, value) {
^
TypeError: Cannot read property 'each' of undefined
我尝试过设置超时和各种调试技术...我不确定为什么它变得未定义;当我将代码放在 html 页面上的标签中时,它工作正常。
爬虫.js:
var Crawler = require("crawler");
var c = new Crawler({
"maxConnections":10,
"callback":function(error, res, $) {
if (error) {
console.log("error");
console.log(error);
} else {
$('a').each(function(index, value) {
console.log($(this).attr('href'));
//c.queue(href)
});
}
}
});
c.queue('http://www.google.com');
最佳答案
问题是您尚未初始化 Cheerio (var $ = res.$;)。
试试这个,它会从提供的 URL 中获取所有点赞...
var Crawler = require("crawler");
var c = new Crawler({
maxConnections: 10,
// This will be called for each crawled page
callback: function(error, res, done) {
if (error) {
console.log(error);
} else {
var $ = res.$;
var links = [];
$('a').each(function(i, elem) {
links[i] = $(this).attr('href');
});
// $ is Cheerio by default
//a lean implementation of core jQuery designed specifically for the server
console.log(links);
}
done();
}
});
c.queue('http://www.google.com');
关于jquery - 使用npm爬虫爬取Node.js错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44298433/