使用Cheerio和Response for Node web scraper,将响应函数结果传递给视图



我正在使用本教程:https://www.smashingmagazine.com/2015/04/web-scraping-with-nodejs/

制作一个真正基本的节点web scraper。我在这里设置并运行了我的应用程序:

https://[修订]/

它目前在我的节点应用程序中的幕后工作是使用两个模块cheerio和request来运行此功能(如下)。这个函数基本上取一个URL,发出请求,用一个数据变量获取页面的一个元素,抓取它的值,并将值(温度)记录到我的计算机终端控制台。我需要一种方法将这个值发送到我的视图并在页面上呈现它,而不仅仅是将它记录到我的计算机控制台。

我遇到的问题是,在下面请求函数的范围内,我无法将任何返回值(温度)传递给我的视图。我知道我的设置有问题,因为我目前在router.get的内部有请求函数。如果我把请求函数放在router.get之外,我仍然无法将值传递到我的视图,但它会成功地从web url中获取数据,并将其记录到我的终端控制台。我希望我是清楚的。请参阅我的视图的res.render,它封装了正在进行web抓取的请求函数。。

router.get('/', function(req, res, next) {
    //target url we are scraping data from
    var url = "http://www.wunderground.com/cgi-bin/findweather/getForecast?&query=" + 02888;
    var temperature;
    // request function that uses the request module
    request(url, function (error, response, body) {
        if (!error) {
            // using cheerio module to load body of html req document and scrape the data
            var $ = cheerio.load(body),
                temperature = $("[data-variable='temperature'] .wx-value").html();
            // logs it to console (of my computer..)    
            console.log("It’s " + temperature + " degrees Fahrenheit.");
        } 
        else {
            console.log("We’ve encountered an error: " + error);
        }
        return temperature;
    });
    /* renders my view, this is my attempt to pass the values as variables to my handlebars template. Currently it is only passing the URL var as it exists before the request function call, and the empty var temperature (which gets its value during, and inside the request function call). How can i get at those values returned from the request function and pass to my view below? */
    res.render('index', {title: url, data: temperature } );  
});

request中的函数是异步执行的,因此,在设置温度之前会调用render。您需要将render函数移到async函数中。

router.get('/', function(req, res, next) {
//target url we are scraping data from
var url = "http://www.wunderground.com/cgi-bin/findweather/getForecast?&query=" + 02888;
var temperature;
// request function that uses the request module
request(url, function (error, response, body) {
    if (!error) {
        // using cheerio module to load body of html req document and scrape the data
        var $ = cheerio.load(body),
            temperature = $("[data-variable='temperature'] .wx-value").html();
        // logs it to console (of my computer..)    
        console.log("It’s " + temperature + " degrees Fahrenheit.");
    } 
    else {
        console.log("We’ve encountered an error: " + error);
    }
    res.render('index', {title: url, data: temperature } );  
});
});

最新更新