【问题标题】:Cheerio how to get text nodes sibling with other tagCheerio 如何获得与其他标签同级的文本节点
【发布时间】:2021-04-26 18:25:51
【问题描述】:

我很久以前就解决了这个问题,但我现在忘记了。 当我的主要选择器是时,我如何访问该日期

$('.date')

let cheerio = require('cheerio')
let html = `
<html>
    <body>
        <span class="date">
            <span class="category">Article</span>
            Sat, 22 Jan 2021 11:12
        </span>
    </body>
</html>`

let $ = cheerio.load(html)

// Empty
console.log($('.date').next().text())
// Empty
console.log($($('.date').children()[0]).next().next().text())
// Empty
console.log($($('.date').children()[0]).next().text())
// Empty
$('.date').each(el => { console.log($(el).text())})

【问题讨论】:

  • 这行得通吗? $('.date').contents().last().text()
  • 哇,我不记得我以前使用过内容,是的!它的工作和添加 .trim() 因为这么多空间谢谢

标签: node.js jquery-selectors cheerio


【解决方案1】:

@Dario 进一步评论:

contents() 函数:

获取匹配元素集中每个元素的子元素,包括文本和注释节点。

所以你可以这样做:

let cheerio = require('cheerio')
let html = `
<html>
    <body>
        <span class="date">
            <span class="category">Article</span>
            Sat, 22 Jan 2021 11:12
        </span>
    </body>
</html>`

let $ = cheerio.load(html)

let val = $('.date').contents().last().text()

console.log(val.trim())
// prints Sat, 22 Jan 2021 11:12

【讨论】:

    猜你喜欢
    • 2023-01-20
    • 2019-07-19
    • 1970-01-01
    • 2018-11-20
    • 1970-01-01
    • 2015-01-27
    • 1970-01-01
    • 2023-03-10
    • 2022-12-29
    相关资源
    最近更新 更多