使用 cheerio 提取 html 元素

extracting html element with cherrio

这个 Meteor 服务器代码使用 cheerio 并尝试提取文本 'John',我尝试了以下几种不同的方法都无济于事。
console.log(e.next.children.eq(1).text()); console.log(e.next.children.last().text()); console.log(e.next.contents().last().text());

用cheerio怎么办?谢谢

ResObj.$("table").contents().filter(function() {
  return this.nodeType == 8;
}).each(function(i, e) {
  if (e.nodeValue.trim() == 'CONTACTS') {
    console.log(e.next.contents('td').eq(1).text()); //<----------
    console.log(e.nextSibling.nodeType);  // returns 3
  }
});


<!-- CONTACTS -->
<tr>
  <td class="label" valign="top" align="right" style="white-space:nowrap">
    Names of people:&nbsp;&nbsp;
  </td>
  <td class="displayValue" valign="top">

    John

  </td>
</tr>

Cheerio 就像 jQuery(大部分情况下),所以当您看起来需要的只是:

时,为什么还要构建这个复杂的结构?
$('table .displayValue').each(function () {
  console.log($(this).text());
});

让我们分解一下您的代码:

// Get all tables contents, then filter the data
ResObj.$("table").contents().filter(function() {
  // Only return Comments? https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType ... also you should be using ===
  return this.nodeType == 8;
// Loop through all of the filtered elements
}).each(function(i, e) {
  // Check the string of the comment for the text you want --- This is bad style
  if (e.nodeValue.trim() == 'CONTACTS') {
    console.log(e.next.contents('td').eq(1).text()); //<----------
    console.log(e.nextSibling.nodeType);  // returns 3
  }
});

那么你经历所有这些循环的原因是为了获得一个具有易于访问的 class 的选择器吗?