11

I am trying to extract just the content of a div - without any of the children of that div - using cheerio. If I just use div.text() - I get all the text - parent and children. Here's the HTML - I just want the value "5.25"

The code below currently returns "Purchase price $5.25"

The HTML below:

<div class="outer tile"> 
    < ... various other html here > 
    <div class="cost">
        <span class="text">Purchase price </span>
        <small>$</small>5.25
    </div>
</div>

with the extract of the relevant node.js CHEERIO code below:

var $ = cheerio.load(data);
$("div.outer.tile").each(function(i, e) {
  var price = $(e).find('div.price');
      console.log(price.text());
});
4

3 回答 3

23

任何人仍然想知道如何在 Cheerio 中做到这一点:

$('div.classname').first().contents().filter(function() {
    return this.type === 'text';
}).text();
于 2014-05-30T13:42:59.687 回答
5

我最喜欢这个:

$('div.cost').children().remove().end().text();

我觉得更简洁(不知道效率)。

资源

运行套件

于 2017-05-27T08:23:29.093 回答
0

我用了这个帖子

使用 jquery 获取 span 元素之后的文本

作为制作小提琴的参考

http://jsfiddle.net/TKwhY/

这对我来说是新的,但是您可以通过仅返回 nodeType 3 的元素来获取文本节点

var a = $('.cost').first().contents().filter(function() {
    return this.nodeType == 3;
});
于 2013-12-30T04:31:33.057 回答