如何将 Cheerio DOM 节点变回 html?

How to turn Cheerio DOM nodes back into html?

使用下面的 HTML,我试图提取每个段落的 html。但是我找不到任何方法将节点变回 HTML 或查询对象。

下面是一个字符串var html = ...

<article>
    <p> p1 </p>
    <p> p2 </p>
</article>

html 是这样加载的

var $ = require('cheerio').load(html)
var paragraphs = $('p').toArray().map(p => /* I want the html at this point */ )

如何获取这些段落的HTML?

注意:为了清楚起见,我将 cheerio.load 的 return 值称为 "query object" 和 toArray 方法的 return DOM节点;因为没有更好的词组。

您可以使用 $.html

var paragraphs = $('p').toArray().map(p => {
    console.log($.html(p));
    return $.html(p);
});

documentation 显示了一个使用选择器的示例,但是 cheerio DOM 元素也按预期工作:

If you want to return the outerHTML you can use $.html(selector):

$.html('.pear') //=> <li class="pear">Pear</li>