使用 cherrio 选择器获取评论元素文本

get the comment element text using cherrio selector

这个 jQuery 类选择器 "cheerio" 试图从 html 页面的评论节点中获取评论。
$ 是 cheerio 对象。 它怎么做到的?谢谢

console.log($('*').contents().length); //reports back more than 1000


$('*').contents().filter(function() {
  if (this.nodeType == 8) {

    //the following gives null for every node found
    console.log($(this).html());

    //the following gives blank for every node found
    console.log($(this).text());
  }
});

评论的内容既不是 HTML (.innerHTML) 也不是值 (.value),而是 .nodeValue。 jQuery 没有为您提供获取该功能的功能,我怀疑 Cheerio 是否也有,但您不需要:只需使用 this.nodeValue:

$('*').contents().filter(function() {
  if (this.nodeType == 8) {
    console.log(this.nodeValue);
  }
});

(我在那里使用了 filter 因为你的例子确实如此,但如果你没有使用 filter 的 return 值,each 更有意义.)

这是一个 DOM 示例,但 Cheerio 可能会以类似方式工作:

$("*").contents().each(function() {
  if (this.nodeType === 8) {
    console.log(this.nodeValue);
  }
});
<!-- Comment 1 -->
<!-- Comment 2 -->
<!-- Comment 3 -->
<!-- Comment 4 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>