首页
学习
活动
专区
圈层
工具
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

NodeJS:使用Cheerio解析HTML HTML和内联SVG图形

Cheerio 是一个 Node.js 库,可用于解析和操作 HTML 文档

  1. 首先,需要在项目中安装 Cheerio。打开终端并运行:
代码语言:javascript
复制
npm install cheerio
  1. 在你的项目中导入 Cheerio 库:
代码语言:javascript
复制
const cheerio = require('cheerio');
  1. 使用 Cheerio 加载 HTML 文档:
代码语言:javascript
复制
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);
  1. 使用 Cheerio 选择器查找和操作 HTML 元素:
代码语言:javascript
复制
// 查找 h1 标签
const h1 = $('h1');
console.log(h1.text()); // 输出: Hello, World!

// 查找 SVG 元素
const svg = $('svg');
console.log(svg.attr('width')); // 输出: 100
  1. 遍历和操作 SVG 内部的元素:
代码语言:javascript
复制
// 查找 SVG 中的 circle 元素
const circle = $('circle');
console.log(circle.attr('fill')); // 输出: red

// 修改 circle 元素的属性
circle.attr('fill', 'blue');
console.log(circle.attr('fill')); // 输出: blue
  1. 将修改后的 HTML 内容输出:
代码语言:javascript
复制
console.log($.html());
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的视频

领券