从 Table Cheerio 获取文本

Getting text from Table Cheerio

从事网络抓取项目时,我无法以统一的方式获取一些数据。该页面有两列 table,我只需要抓取第二列的文本即可 运行 编译值。

我是这样处理的:

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

rq(url, (err, res, html) => {
    let $ = cheerio.load(html);
    $('#table-id > tbody > tr > td.data').toArray().map(item => {
        console.log(item.text());
    });
});

但是我得到一个错误,提示 .text() 不是一个函数。

.text() 是一种 cheerio 方法,因此要使用它,您需要将项目设为 cheerio 元素

这应该有效:

console.log($(item).text())

您必须用 $() 包裹 item,才能将其转换为 cheerio 元素。

$('#table-id > tbody > tr > td.data').toArray().map(item => {
  console.log($(item).text());
});

您也可以使用 .each 并删除 toArraymap。并使用 $(this) 来引用当前元素。

$('#table-id > tbody > tr > td.data').each(() => {
   console.log($(this).text());
});