NodeJS Cheerio,抓取和获取变量

NodeJS Cheerio, scraping & get variables

我需要从没有 API 的站点获取一些统计信息。查看源代码后,我看到了(我需要的)数据是用来构建统计图形的。

我能够使用 Request & Cheerio 获取脚本标签:

request(nodeUrl, function(error, res, body) {
    var $ = cheerio.load(body);

    var scripts = $('script').filter(function() {
        return ($(this).html().indexOf('Dygraph(document') > -1);
    });
    if (scripts.length === 1) {
        var text = $(scripts[0]).html();
        console.log(text);
    }
});

我需要的数据(使用 js 格式化程序以便于阅读并删除所有其他脚本):

d = new Dygraph(document.getElementById("container"), [
    [new Date("2017/08/01"), 0.0654],
    [new Date("2017/08/02"), 0.257],
    [new Date("2017/08/03"), 0.245],
    [new Date("2017/08/04"), 0.15],
    [new Date("2017/08/05"), 0.107],
    [new Date("2017/08/06"), 0.109],
    [new Date("2017/08/07"), 0.143],
    [new Date("2017/08/08"), 0.222],
    [new Date("2017/08/09"), 0.166],
    [new Date("2017/08/10"), 0.156],
    [new Date("2017/08/11"), 0.143],
    [new Date("2017/08/12"), 0.199]
]);

我只需要全部:[new Date("2017/08/12"), 0.199]

任何建议都会很棒。提前致谢。

您可以使用正则表达式来解析数据。

var re = /new Date\("([0-9]{4}\/[0-9]{2}\/[0-9]{2})"\), ([0-9]+\.[0-9]+)/g;
var m;
do {
    m = re.exec($(scripts[0]).html());

    // scraped data:
    // [new Date(m[1]), m[2]]
}
while (m)