【问题标题】:extracting html element with cherrio用cheerio提取html元素
【发布时间】:2016-06-10 22:24:46
【问题描述】:

此 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>

【问题讨论】:

    标签: html meteor cheerio


    【解决方案1】:

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

    他们为什么要经历所有这些循环,只是为了获得一个具有易于访问的类的选择器的原因?

    【讨论】:

      猜你喜欢
      • 2023-03-18
      • 2017-09-07
      • 2022-11-26
      • 2020-07-06
      • 2016-09-22
      • 1970-01-01
      • 2017-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多