gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:09:31 24 4
gpt4 key购买 nike

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

这是url我正在刮。

这是我用来返回列的 Cheerio 选择器。我想要的内容位于带有“排序”类的标签 th 上。

$('.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());
});
}
}
);

感谢您的帮助!

最佳答案

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

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

关于javascript - 无法在 Cheerio 中显示选择器内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59603769/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com