使用Cheerio的Nodejs Webscraping函数在完成之前返回

问题描述 投票:0回答:2

我目前正在研究一个简单的Web抓取Node.js程序。它基于cheerio,我从网站上获取商品并从中提取一些信息。

据我了解,我在foreach循环中调用的所有函数都是同步的,因此它们应自上而下执行。而且因为foreach循环也是一个普通循环,该循环在js中执行同步,所以该函数应该返回我完成的数组。但是相反,它变得不确定,当我直接将其登录到控制台中时,它可以正常工作(?)。

function getIntensiv(){
    var intensivregister = [];
    request.post({url: 'SOMEURL', form: {SOMEFORM}}, function(err,res,body){
        var $ = cheerio.load(body);
        $('#dataList').children('tbody').children('tr').each(function(i, elem){
            var name = $(elem).children('td').first().text().trim().split("\n")[0].trim();                        
            var zipcity = $(elem).children('td').first().children('small').last().text();                         
            var streetnr = $(elem).children('td').first().children('br').last().prev().text();                    
            intensivregister.push({'name': name, 'zipcity': zipcity, 'streetnr': streetnr});
        });
        console.log(intensivregister);  //works and prints the finished array
        return intensivregister;        //returns undefined before function finished
    });
}

如果您能向我解释我的错误所在并帮助我解决它,我将不胜感激。

javascript node.js asynchronous web-scraping cheerio
2个回答
0
投票
function getIntensiv(){
const cheerio = require('cheerio')
const request = require('request')

var intensivregister = [];
request.get({url: 'https://www.w3schools.com/html/html_tables.asp'}, function(err,res,body){


var $ = cheerio.load(body);

    $('#customers').children('tbody').children('tr').each(function(i, elem){
        var name = $(elem).children('td').first().text().trim().split("\n")[0].trim();                        
        var zipcity = $(elem).children('td').first().children('small').last().text();                         
        var streetnr = $(elem).children('td').first().children('br').last().prev().text();                    
        intensivregister.push({'name': name, 'zipcity': zipcity, 'streetnr': streetnr});
    });
    console.log(intensivregister);  //works and prints the finished array
    return null;        //returns undefined before function finished
});
return null;   //***<---This is returning and not the above return. If no return statement is written then undefined is passed.***
};

var retrunVal = getIntensiv()
console.log(retrunVal);

请找到突出显示的评论


0
投票

好吧,我发现我对javascript的想法不是应该如何使用它。我解决了我的问题,摆脱了从函数返回值的想法(这主要是基于异步编程的经验),而是使用了回调函数,该参数提供给函数并在请求结束时调用。

function getIntensiv(callback){
    var intensivregister = [];
    request.post(...);
    **callback(intensivregister);**
}

[可行的方法(我认为是更好的解决方案)也在使用promises请求承诺,并在finally调用中调用回调。

© www.soinside.com 2019 - 2024. All rights reserved.