jquery 使用cheerio选择表格页脚值

9w11ddsr  于 2023-03-07  发布在  jQuery
关注(0)|答案(2)|浏览(101)

抓取页面后,我使用cheerio选择了表的页脚:

const $ = cheerio.load(data);
const foot = $('#tblAcctBal > tfoot > tr');
o = $(foot).html();
console.log(o);

结果显示为以下html:

tr> <th rowspan=\"1\" colspan=\"1\"></th>
<th rowspan=\"1\" colspan=\"1\"></th>
<th rowspan=\"1\" colspan=\"1\"></th>
<th rowspan=\"1\" colspan=\"1\"></th>
<th rowspan=\"1\" colspan=\"1\"></th>
<th rowspan=\"1\" colspan=\"1\">$0.00</th>
<th rowspan=\"1\" colspan=\"1\">$0.00</th>
<th rowspan=\"1\" colspan=\"1\">$0.00</th>
<th rowspan=\"1\" colspan=\"1\">$0.00</th>
<th rowspan=\"1\" colspan=\"1\">$0.00</th>undefined</tr>\n

我正在尝试获取页脚中的文本值数组。我尝试过:

$(foot).each( function (th) {
    console.log($(th).text().trim())
  })

但没有输出,怎么解决

xwbd5t1u

xwbd5t1u1#

选择th元素并在这些元素上循环。

const feet = $('#tblAcctBal > tfoot > tr > th');

for (const el of feet){
  console.log($(el).text())
}

const values = feet
  .map((i, el) => $(el).text())
  .toArray()

console.log(values)

顺便说一句,cheerio中的.each()和其他迭代函数在函数签名中提供了indexelement

feet.each((index, el) => {
  console.log(index, $(el).text())
})

在示例代码中,选择器返回一个tr元素,它需要类似.children()的内容来获取每个th元素。

const row = $('#tblAcctBal > tfoot > tr')
console.log(row.length) // 1
$(row).children().each((i, el) => {
  console.log(i, $(el).text())
})
46scxncf

46scxncf2#

如果他们真在那里,你可以做:

$('tfoot tr th').get().map(el => $(el).text())

相关问题