javascript - 使用 Cheerio 和 Response for Node 网络抓取工具,将响应函数结果传递到 View

标签 javascript node.js request handlebars.js cheerio

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

制作一个真正基本的 Node 网络抓取工具。我在这里设置并运行了我的应用程序:

https://[redacted]/

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

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

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 函数移至异步函数中。

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 } );  
});

});

关于javascript - 使用 Cheerio 和 Response for Node 网络抓取工具,将响应函数结果传递到 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34685719/

相关文章:

iphone - IOS5 - AFNetworking 处理请求

Javascript promise 返回意外的 token 错误

javascript - AngularJS - 删除 Hashbang 后页面重新加载时出现 404 错误

javascript - JavaScript 中的数字选择器

javascript - 如何在 node-red node exec 中运行命令以启用 LCD 脚本

php - 检查数据并将其插入MySQL数据库 Node 的有效方法

javascript - 在 javascript 中比较 NaN

javascript - 秒表计时器无法正常工作

javascript - 为什么 plyr 没有在任何浏览器中以全屏模式全屏播放视频

java - RoboSpice:如何在 SpiceRequest 中触发 RequestListener.onRequestFailure 方法