简体   繁体   English

用cherrio提取html元素

[英]extracting html element with cherrio

This Meteor server code uses cheerio and tries to extract the text 'John', I tried the few different ways below for no avail. 该流星服务器代码使用了cheerio并尝试提取文本“ John”,我尝试了以下几种不同的方法,但无济于事。
console.log(e.next.children.eq(1).text()); console.log(e.next.children.last().text()); console.log(e.next.contents().last().text());

How can it be done with cheerio? 如何用cheerio完成? Thanks 谢谢

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 is just like jQuery (for the most part), so why are you building this complex structure when all it look like you need is: Cheerio就像jQuery(在大多数情况下)一样,所以为什么要构建这种复杂的结构,而看起来却只需要:

$('table .displayValue').each(function () {
  console.log($(this).text());
});

Let's break down the code you have: 让我们分解一下您拥有的代码:

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

So are their reasons why you are going through all these loops, just to get a selector that has a class which is easily accessible? 那么,为什么要遍历所有这些循环,只是为了获得一个具有易于访问的类的选择器,是他们的原因吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM