【问题标题】:Can't display selectors content in Cheerio无法在 Cheerio 中显示选择器内容
【发布时间】:2020-04-23 12:07:10
【问题描述】:

我正在尝试从网站中提取表格,并希望首先获取所有列。发出请求后,我将 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());
            });
        }
    }
);

感谢您的帮助!

【问题讨论】:

  • 排序类是js加载后添加的,可以查看源码查看,raw html中没有sorting

标签: javascript node.js web-scraping request cheerio


【解决方案1】:

在原始 HTML 中,没有名为 sorting 的类,因为 javascript 会动态地将此类添加到 dom,因此在这种特定情况下,通过使用以下代码,您可以收集嵌入在 @987654323 中的所有 th 标记的内容@标签的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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 2010-12-15
    • 2015-12-18
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 1970-01-01
    相关资源
    最近更新 更多