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



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

感谢您的帮助!

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

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

最新更新