Cheerio 如何让文本节点与其他标签同级
Cheerio how to get text nodes sibling with other tag
很久以前解决过,现在忘记了。
当我的主要选择器是
时,我如何访问该日期
$('.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()函数:
Gets the children of each element in the set of matched elements, including text and comment nodes.
所以你可以这样做:
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
很久以前解决过,现在忘记了。 当我的主要选择器是
时,我如何访问该日期$('.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()函数:
Gets the children of each element in the set of matched elements, including text and comment nodes.
所以你可以这样做:
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