我正在尝试构建一个小脚本来收集一些数据。我有一些 javascript 的基础知识,但是我有点迷失了所有异步回调或 promise 的东西。这是我现在拥有的:
url = "http://Blablablabla.com";
var shares = function(req, res) {
request(url, function (error, response, body) {
if (!error) {
var $ = cheerio.load(body),
share = $(".theitemIwant").html();
return res.send(url + ":" + share);
} else {
console.log("We've encountered an error: " + error);
}
})
}
所以这段代码一切正常。我想做的是:
- 使用 url 数组
var urls = [url1,url2,url3,etc...]
- 将我的废弃数据存储到另一个数组中,类似这样的
data = [{url: url1, shares: share},{url: url2, shares: share},etc...]
>/li>
我知道我需要使用这样的东西 data.push({ urls: url, shares: share})})
我知道我需要遍历我的第一个 url 数组以将数据推送到我的第二个数据数组中。
然而,我对 request
方法以及在我的情况下处理异步问题的方式有点迷茫。
谢谢!
编辑#1:
我试过使用 promises :
var url = "www.blablabla.com"
var geturl = request(url, function (error, response, body) {
if (!error) { return $ = cheerio.load(body) } else
{ console.log("We've encountered an error: " + error); }
});
var shares = geturl.then( function() {
return $(".nb-shares").html();
})
但出现以下错误 geturl.then is not a function
最佳答案
我认为你应该使用 async :
var async = require('async');
var urls = ["http://example.com", "http://example.com", "http://example.com"];
var data = [];
var calls = urls.map((url) => (cb) => {
request(url, (error, response, body) => {
if (error) {
console.error("We've encountered an error:", error);
return cb();
}
var $ = cheerio.load(body),
share = $(".theitemIwant").html();
data.push({ url, share })
})
})
async.parallel(calls, () => { /* YOUR CODE HERE */ })
你可以对 promise 做同样的事情,但我不明白为什么。
关于javascript - Node.js 网络抓取,在 URL 数组上循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39649237/