【问题标题】:Cheerio returns undefined when using the "contains" selectorCheerio 在使用“包含”选择器时返回未定义
【发布时间】:2018-11-14 03:47:21
【问题描述】:

我目前正在尝试解析来自this URL 的一些 HTML:

我关注的主要信息是列出的Weight。使用 Chrome 中的控制台,我可以发出命令:

$("th:contains(Weight)").parent()[0];

它会给我表格行,其中包含我需要的关于重量的所有信息。

我尝试在 Cheerio 中使用它,但它只返回 undefined。 这是我的 Node.js 代码:

var needle = require('needle');
var cheerio = require('cheerio');

function rei(product) {
    //Request page from rei.com and follow the redirect
    return needle("get", "https://rei.com/product/" + product, {
        follow_max: 5
    }).then(function(response) {
        var $ = cheerio.load(response.body);

        var test = $("th:contains(Weight)").parent()[0];
        console.log(test);
    }).catch(function(error) {
        console.log(error);
    })
};
rei(893905);

以自动方式从 Rei 的网站获取我需要的信息的最佳方式是什么?

【问题讨论】:

  • 在 chrome 中查看页面源代码。数据在页面上,但它是 json,所以你必须解析它。
  • 你应该读取响应数据,(不是浏览器中呈现的html)

标签: node.js cheerio


【解决方案1】:

试试这个:

var needle = require('needle');
var cheerio = require('cheerio');
var fs = require('fs');

function rei(product) {
    //Request page from rei.com and follow the redirect
    return needle("get", "https://rei.com/product/" + product, {
        follow_max: 5
    }).then(function(response) {
        var $ = cheerio.load(response.body);

        // your data in script
        var content = $('script[data-client-store="product-details"]').html();

        content = JSON.parse(content);

        for (var spec of content.specs) {
            if (spec.name == 'Weight') {
                console.log(spec.values)
            }
        }

    }).catch(function(error) {
        console.log(error);
    })
};
rei(893905);

【讨论】:

    猜你喜欢
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 2020-08-31
    • 2014-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多