Cheerio 如何让文本节点与其他标签同级

问题描述

我很久以前就解决了这个问题,但我现在忘记了。 当我的主选择器为

时,我如何访问该日期

$('.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())})

解决方法

@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