Cheerio:在带有标签的儿童上循环

问题描述 投票:0回答:1

我正在尝试遍历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);
javascript jquery node.js web-scraping cheerio
1个回答
0
投票

设法通过使用cheerio.html($(el))来解决它,这在他们的文档here中已指出

outerHTML取得非常相似的结果。

© www.soinside.com 2019 - 2024. All rights reserved.