首页 > 开发 > MySQL > 正文

用nodejs的request模块爬多个网页的问题?

2017-09-08 09:04:39  来源:网友分享

我现在有很多网页要爬,这些地址我已经爬下来放在一个数组里,然后我想用for循环抓取这些网页,代码如下:

db_operation.db_getUrl('appsCategories_China', function(results){            for(var i = 0; i < results.length; i++)            {                var item = results[i];                // console.log(item);                request(item.url, function(err, res, content){                    if(!err && res.statusCode == 200)                    {                        $$ = cheerio.load(content);                        getAppsIndex('#selectedcontent', 'a', function(index){                            console.log(i);                            index.push(item.category);                            console.log(item.category);                            // db_operation.db_addIndex('appsIndex_China', index)                        });                    }                });            }}

结果最后两个控制台输出都是数组results的最后一个元素,应该是因为request的异步执行,导致for循环完了,request还没返回。想请问下我是不是不应该用for循环?求指导!

解决方案

用循环可以的,坐下修改~~
使用闭包来封装变量

db_operation.db_getUrl('appsCategories_China', function(results){    for(var i = 0; i < results.length; i++)    {        var item = results[i];        (function(i,item ){             request(item.url, function(err, res, content){                if(!err && res.statusCode == 200)                {                    $$ = cheerio.load(content);                    getAppsIndex('#selectedcontent', 'a', function(index){                        console.log(i);                        index.push(item.category);                        console.log(item.category);                        // db_operation.db_addIndex('appsIndex_China', index)                    });                }            });        }(i,item ));    }}