node解析html之cheerio

概述

cheerio 是 node 的第三方模块,使用语法和 jquery 类似,可以使用 cheerio 来解析 html 文件,进而对文件进行修改等操作。

安装

1
npm install cheerio

示例

下面示例会读取 test.html 文件,然后修改其 #wraper 节点的内容。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>

<body>
<div id="wraper">hello</div>
</body>

</html>

在文件 modfiyhtml.js 中操作 test.html 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const fs = require("fs");
const path = require("path");
const cheerio = require("cheerio");//引用第三方库
const fName = path.join(process.cwd(), "./test.html");

if (fs.existsSync(fName)) {
fs.readFile(fName, "utf-8", function(err, data) {
$ = cheerio.load(data);
$("#wraper").html("world");// 修改#wraper 节点内容

console.log($.html());//输出修改后的内容
});
} else {
console.log("not exist");
}

输出结果:

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>

<body>
<div id="wraper">world</div>


</body></html>