我正在从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
的一个级别?
答案 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()
即可使段落嵌套变平。