首页 > 解决方案 > 如何查询cheerio以获取包含选择器标签的html输出

问题描述

如果您使用$("body").html()cheerio,则返回body 标签内的html。如何查询 Cheerio 的body包含开始和结束body标签的内容?

以这样的文件为例:

<body class="body">
 <div>
  <h1>Foo Bar</h1>
 </div>
</body>

<style>
.body {
 margin: 0;
}
</style>

以下代码将html输出body. 输出将不包含<body>标签,这是我想要实现的

const cheerio = require("cheerio");
const $ = cheerio.load(text);
const body = $("body").html();

console.log(body);
// <div>
//  <h1>Foo Bar</h1>
// </div>

标签: javascript

解决方案


使用$.html("body")而不是$("body").html().


推荐阅读