无法在Cheerio中显示选择器内容

问题描述 投票:0回答:1

我正在尝试从网站提取表格,并希望首先获取所有列。发出请求后,我将html加载到cheerio中,但是当我尝试显示选择器内容时,控制台上没有任何内容。让我感到困惑的是,当我直接在页面控制台上尝试使用相同的选择器时,它起作用并向我展示了所有这些选择器。

这里是我要抓取的url

这里是我用来返回列的cheerio选择器。我想要的内容在标签“类别”上。

$('.sorting').each(function (index, element) {
                const $element = $(element);
                console.log($element.text());
            });

这是完整的代码。

const request = require('request');
const cheerio = require('cheerio');

const fundsExplorerUrl = 'https://www.fundsexplorer.com.br/ranking';

request(fundsExplorerUrl,
    function (error, response, body) {
        if (!error && response.statusCode == 200) {
            const $ = cheerio.load(body);

            $('.sorting').each(function (index, element) {
                const $element = $(element);
                console.log($element.text());
            });
        }
    }
);

感谢您的帮助!

javascript node.js web-scraping request cheerio
1个回答
0
投票

在原始HTML中,没有名为sorting的类,因为javascript正在将此类动态添加到dom中,因此在此特定情况下,通过使用以下代码,您可以收集th中嵌入的所有thead标签的内容table标签的标签。

const request = require('request-promise');
const cheerio = require('cheerio');

const url = 'https://www.fundsexplorer.com.br/ranking';

async function crawl() {
    const rawHtml = await request(url);
    const $ = cheerio.load(rawHtml);

    $('table thead tr th')
        .each( (index, element) => {
        console.log($(element).text());
    })
}

crawl();

© www.soinside.com 2019 - 2024. All rights reserved.