与cheerio DOM遍历 - 如何获得
问题描述:
所以我用Cheerio,类似的jQuery的节点服务器端库,它允许您解析HTML文本并遍历与其相应的文本的所有元素它就像你会用jQuery一样。我需要获取html正文的纯文本,但不仅如此,我需要获取相应的元素和数字。 IE:如果纯文本是在第三段元素中找到,我会是这样的:与cheerio DOM遍历 - 如何获得
{
text: <element plaintext>,
element: "p-3"
}
我现在有下面的函数试图做到这一点:
var plaintext_elements = traverse_tree($('body'));
function traverse_tree(root, found_elements = {}, return_array = []) {
if (root.children().length) {
//root has children, call traverse_tree on that subtree
traverse_tree(root.children().first(), found_elements, return_array);
}
root.nextAll().each(function(i, elem) {
if ($(elem).children().length) {
//if the element has children call traverse_tree on the element's first child
traverse_tree($(elem).children().first(), found_elements, return_array)
}
else {
if (!found_elements[$(elem)[0].name]) {
found_elements[$(elem)[0].name] = 1;
}
else {
found_elements[$(elem)[0].name]++
}
if ($(elem).text() && $(elem).text != '') {
return_array.push({
text: $(elem).text(),
element: $(elem)[0].name + '-' + found_elements[$(elem)[0].name]
})
}
}
})
if (root[0].name == 'body') {
return return_array;
}
}
我要去的正确的方向,我应该尝试别的吗?任何帮助,将不胜感激。再次,这是而不是jQuery,但Cheerio在服务器端。 (他们都非常相似,不过)
答
我认为,如果你使用*
CSS选择
function textElements($){
const found = {}
return $('body *').map(function(el){
if ($(this).children().length || $(this).text() === '') return
found[this.name] = found[this.name] ? 1 + found[this.name] : 1
return {
text: $(this).text(),
element: `${this.name}-${found[this.name]}`,
}
}).get()
}
textElements(cheerio.load(html)
从当前的代码看起来你很高兴忽略具有的元素并不需要大量的遍历儿童和文本?像'
text
dt中的'dt'是的,这是我碰到的问题之一。我不知道如何处理这种情况,没有得到大量的重复,就像说'blah blah blah''会为td和a都拿起“blah blah blah”。 – janedoe