如何重写HTML以替换与子代标记相同的父代标记?

时间:2019-06-27 19:14:34

标签: jquery html cheerio

我正在从API读取大量HTML内容

[
    {
        id: 1,
        content: '{html...}'
    },
    {
        id: 2,
        content: '{html...}'
    }
]

获取此数据后,我使用sanitize-html做一些替换。但是现在我必须做一些额外的工作。

有时候我明白了

<p>some text...<p>
<p>
    <p>some text...<p>
    <p>
        <img />
        <span>some text</span>
    <p>
<p>

或这个

<p>some text...<p>
<p>some text...<p>
<p>
    <img />
    <span>some text</span>
<p>

我假装要做的是将段落保持在一个级别,所以我想使用cheerio(使用jQuery核心),做类似的事情

const cheerio = require('cheerio');
const $ = cheerio.load(content);
content = $('p:not(:has(>p))').html();

但是,这只会带来第一个p并且只有在存在的时候。如果我确实手动获取其他内容,则可能会丢失正确的内容顺序。

因此,根据我的示例,有没有一种很好的方法可以清理HTML,使其仅保留p的一个级别?

1 个答案:

答案 0 :(得分:1)

您的HTML无效。

  • p元素不能包含p元素
  • p的结束标记是可选的
  • 尝试将p放在另一个p内将隐式关闭第一个p
  • 多余的结束标签将被忽略

该程序:

const content = `

<p>some text...<p>
<p>
    <p>some text...<p>
    <p>
        <img />
        <span>some text</span>
    <p>
<p>


`;

const cheerio = require('cheerio');
const $ = cheerio.load(content);
console.log($.html());

将输出以下内容:

<html><head></head><body><p>some text...</p><p>
</p><p>
    </p><p>some text...</p><p>
    </p><p>
        <img>
        <span>some text</span>
    </p><p>
</p><p>


</p></body></html>

因此,只需调用$.html()即可使段落嵌套变平。