我正在用node.js和Electron构建一个网络爬虫。
本质上,该程序接受一个起始URL,并爬行到一定深度,报告它在哪里找到了某些关键字。
到目前为止,这是有效的,但我不知道如何实际判断它何时完成。给出3-4的深度,这个程序似乎永远都会运行。对于较低的深度,真正判断它是否仍在爬行的唯一方法是查看它正在使用的CPU/内存量。
下面是执行抓取的函数:
function crawl(startingSite, depth) {
if (depth < maxDepth) {
getLinks(startingSite, function (sites) { //pulls all the links from a specific page and returns them as an array of strings
for (var i = 0; i < sites.length; i++) { //for each string we got from the page
findTarget(sites[i], depth); //find any of the keywords we want on the page, print out if so
crawl(sites[i], depth + 1); //crawl all the pages on that page, and increase the depth
}
});
}
}
我的问题是,我不知道如何让这个函数在完成时返回报告。
我尝试了这样的东西:
function crawl(startingSite, depth, callback) {
if (depth < maxDepth) {
getLinks(startingSite, function (sites) { //pulls all the links from a specific page and returns them as an array of strings
for (var i = 0; i < sites.length; i++) { //for each string we got from the page
findTarget(sites[i], depth); //find any of the keywords we want on the page, print out if so
crawl(sites[i], depth + 1); //crawl all the pages on that page, and increase the depth
}
});
}
else
{
callback();
}
}
但显然,callback()会立即被调用,因为爬虫很快就会命中深度并退出if语句。
我所需要的就是这个函数在它的所有递归实例完成爬行并达到最大深度后立即打印出来(例如输出到console.log )。
有什么想法吗?
发布于 2018-04-19 03:23:51
你可以使用promises:
const links = (start) =>
new Promise(res => getLinks(start, res));
async function crawl(startingSite, depth) {
if (depth >= maxDepth)
return;
const sites = await links(startingSite);
for (const site of sites) {
await findTarget(site, depth);
await crawl(site, depth + 1);
}
}
那就这样做:
crawl(something, 0).then(() => console.log("done"));
https://stackoverflow.com/questions/49907347
复制相似问题