【发布时间】:2013-09-28 22:08:56
【问题描述】:
我正在尝试使用 'request' 和 'cheerio' 编写 scraper。我有一个包含 100 个网址的数组。我正在遍历数组并在每个网址上使用“请求”,然后执行 Cheerio.load(body)。如果我将 i 增加到 3 以上(即,将其更改为 i nodeJS - Using a callback function with Cheerio 似乎同意。
我的问题是我不明白如何确保网页已“加载”或在循环的每次迭代中被解析,这样我就不会得到任何未定义的变量。根据另一个答案,我不需要回调,但是我该怎么做呢?
for (var i = 0; i < productLinks.length; i++) {
productUrl = productLinks[i];
request(productUrl, function(err, resp, body) {
if (err)
throw err;
$ = cheerio.load(body);
var imageUrl = $("#bigImage").attr('src'),
productNumber = $("#product").attr('class').split(/\s+/)[3].split("_")[1]
console.log(productNumber);
});
};
输出示例:
1461536
1499543
TypeError: Cannot call method 'split' of undefined
【问题讨论】:
-
你遇到了什么错误?
-
添加到问题中,不能调用未定义的拆分。如果我删除拆分并仅打印出 imageUrl 和/或 productNumber,则设置了一些变量但很多未定义,这使我相信循环在网页响应之前继续进行?
标签: node.js asynchronous cheerio