【问题标题】:Cheerio: Loop over children with tagsCheerio:用标签循环孩子
【发布时间】:2020-03-13 12:43:03
【问题描述】:

我正在尝试遍历 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>

但是结果给了我里面每个孩子的一切,这不是我想要的。我想保留他们各自的&lt;p&gt;&lt;div&gt; 标签。

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

console.log($(el).prop('outerHTML'));
console.log($(el).outerHTML);
console.log($(el)[0].outerHTML);

【问题讨论】:

  • 尝试使用 'childNodes' 而不是 'children' 并过滤掉不需要的节点。

标签: javascript jquery node.js web-scraping cheerio


【解决方案1】:

设法通过使用cheerio.html($(el)) 来解决它,如他们的文档here 中所述

这实现了与outerHTML 非常相似的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-19
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多