Cheerio 是一个 Node.js 库,可用于解析和操作 HTML 文档
npm install cheerio
const cheerio = require('cheerio');
const html = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Example Page</title>
</head>
<body>
<h1>Hello, World!</h1>
<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>
</body>
</html>
`;
const $ = cheerio.load(html);
// 查找 h1 标签
const h1 = $('h1');
console.log(h1.text()); // 输出: Hello, World!
// 查找 SVG 元素
const svg = $('svg');
console.log(svg.attr('width')); // 输出: 100
// 查找 SVG 中的 circle 元素
const circle = $('circle');
console.log(circle.attr('fill')); // 输出: red
// 修改 circle 元素的属性
circle.attr('fill', 'blue');
console.log(circle.attr('fill')); // 输出: blue
console.log($.html());
领取专属 10元无门槛券
手把手带您无忧上云