【问题标题】:NodeJS Cheerio, scraping & get variablesNodeJS Cheerio,抓取和获取变量
【发布时间】:2017-12-09 02:31:02
【问题描述】:

我需要从没有 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]

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

【问题讨论】:

    标签: javascript parsing web-scraping text-parsing cheerio


    【解决方案1】:

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

    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)
    

    【讨论】:

    • 谢谢!。我看到有一些空值,不是在日期(第一个参数)中,而是在值(第二个参数)中。我试过:[new Date("([0-9]{4}\/[0-9]{2}\/[0-9]{2})"),(*)],但它没有匹配它。例如:[new Date("2017/10/29"),null]
    • 找到它:[new Date("([0-9]{4}\/[0-9]{2}\/[0-9]{2})"),( [0-9]\.[0-9]+|null)]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多