Cheerio возвращает неопределенное значение при использовании селектора «содержит» - PullRequest
0 голосов
/ 04 июня 2018

В настоящее время я пытаюсь проанализировать некоторый HTML-код из этого URL-адреса :

Основная информация, которую я запрашиваю, - это перечисленные 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);

Как лучше всего получать необходимую информацию с веб-сайта Рей в автоматическом режиме?

1 Ответ

0 голосов
/ 17 июля 2018

Попробуйте это:

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