Cheerio:带标签的儿童环游

我正在尝试遍历tag的子级,我想保留它们各自的tags。例如:

<div class='main'>
    <p>First p</p>
    <div class='1'>Div 1</div>
    <div class='2'>Div2 <p>Another P</p></div>
</div>

我想像这样遍历孩子们

<p>First p</p>
<div class='1'>Div 1</div>
<div class='2'>Div2 <p>Another P</p></div>

我正在尝试的代码如下:

const block = body.find('div.main')
const children = block.children().each((i,el) => {
   console.log("===")
   console.log($(el).html()) //Also tried $(this).html(),but returns null
})

结果:

===
First p
===
Div 1
===
Div2 <p>Another P</p>

但是结果给了我每个孩子里面的一切,这不是我想要的。我想保留它们各自的<p><div>标签。

其他尝试使用outerhtml的尝试似乎不起作用,即它们都返回了undefined。我尝试过的事情:

console.log($(el).prop('outerhtml'));
console.log($(el).outerhtml);
console.log($(el)[0].outerhtml);
mm6yuz 回答:Cheerio:带标签的儿童环游

设法通过使用cheerio.html($(el))来解决此问题,这正如他们的文档here

所示

outerHTML的结果非常相似。

本文链接:https://www.f2er.com/3082993.html

大家都在问