🚀 Cheerio 完全用法指南

服务器端 jQuery - 快速、灵活、简洁的 HTML 解析工具

📖 什么是 Cheerio?

Cheerio 是一个快速、灵活、轻量级的库,用于在服务器端解析和操作 HTML。它提供了类似 jQuery 的 API,让您能够使用熟悉的语法来处理 HTML 文档。

主要特点:

⚡ 快速

基于 htmlparser2,解析速度极快

🎯 熟悉

jQuery 风格的 API,上手简单

🔧 灵活

支持多种解析选项和插件

📦 轻量

无浏览器依赖,体积小

📥 加载 HTML

基本用法

const cheerio = require('cheerio'); // 从字符串加载 const html = '<div class="example">Hello World</div>'; const $ = cheerio.load(html); // 从文件加载(Node.js) const fs = require('fs'); const htmlContent = fs.readFileSync('index.html', 'utf8'); const $ = cheerio.load(htmlContent);

加载选项

选项 描述 示例
xmlMode 启用 XML 模式 cheerio.load(html, {xmlMode: true})
decodeEntities 解码 HTML 实体 cheerio.load(html, {decodeEntities: false})
lowerCaseAttributeNames 小写属性名 cheerio.load(html, {lowerCaseAttributeNames: false})

🎯 选择器

示例 HTML

const html = ` <div id="main" class="container"> <h1 class="title">Welcome</h1> <ul class="list"> <li class="item active">Item 1</li> <li class="item">Item 2</li> <li class="item">Item 3</li> </ul> <div class="content"> <p>Hello <span class="highlight">World</span></p> <a href="https://example.com" data-id="123">Link</a> </div> </div> `; const $ = cheerio.load(html);

基本选择器

ID 选择器

$('#main') // 结果: <div id="main" class="container">...

类选择器

$('.item') // 结果: 所有带有 item 类的元素

标签选择器

$('h1') // 结果: <h1 class="title">Welcome</h1>

属性选择器

$('[data-id="123"]') // 结果: <a href="https://example.com" data-id="123">Link</a>

组合选择器

// 子元素选择器 $('ul > li') // 后代选择器 $('.content p') // 相邻兄弟选择器 $('.item.active + .item') // 通用兄弟选择器 $('.item.active ~ .item') // 多选择器 $('h1, .item, a') // 过滤选择器 $('li').filter('.active') $('li').not('.active')

🏷️ 属性操作

获取属性

$('a').attr('href') // 结果: "https://example.com" $('a').attr('data-id') // 结果: "123"

设置属性

$('a').attr('target', '_blank') // 设置 target="_blank" $('img').attr({ src: 'image.jpg', alt: 'Description' })

移除属性

$('a').removeAttr('data-id') // 移除 data-id 属性

hasClass / addClass / removeClass / toggleClass

$('li').hasClass('active') // 结果: true $('li').addClass('new-class') $('li').removeClass('active') $('li').toggleClass('active')

📝 内容操作

text() - 获取/设置文本内容

$('.title').text() // 结果: "Welcome" $('.title').text('New Title') // 设置新文本

html() - 获取/设置 HTML 内容

$('.content').html() // 结果: "<p>Hello <span class="highlight">World</span></p>..." $('.content').html('<p>New HTML</p>')

val() - 获取/设置表单值

// 假设有 <input value="default"> $('input').val() // 结果: "default" $('input').val('new value')

🔄 遍历方法

查找元素

// 查找子元素 $('.list').children() $('.list').children('.active') // 查找父元素 $('.item').parent() $('.item').parents() $('.item').parentsUntil('.container') // 查找兄弟元素 $('.item.active').siblings() $('.item').next() $('.item').prev() $('.item').nextAll() $('.item').prevAll()

过滤方法

first() / last() / eq()

$('.item').first() $('.item').last() $('.item').eq(1) // 第二个元素

filter() / not()

$('.item').filter('.active') $('.item').not('.active')

find()

$('#main').find('span') // 在 #main 内查找 span

each() - 遍历

$('.item').each((i, elem) => { console.log($(elem).text()) })

🛠️ DOM 操作

插入方法

// 内部插入 $('.list').append('<li>New Item</li>') $('.list').prepend('<li>First Item</li>') // 外部插入 $('.item').after('<li>After Item</li>') $('.item').before('<li>Before Item</li>') // 包裹元素 $('.highlight').wrap('<strong></strong>') $('.highlight').wrapInner('<em></em>')

修改和移除

移除元素

$('.item').remove() $('.item').empty() // 清空内容

替换元素

$('.item').replaceWith('<div>New Element</div>')

克隆元素

const clone = $('.item').clone()

🚀 高级用法

序列化

// 获取整个 HTML $.html() // 或者 $('body').html() // 获取选择器的 HTML $('.container').html()

实用工具

长度和索引

$('.item').length // 结果: 3 $('.item').index('.active') // 结果: 0

转换为数组

$('.item').toArray() // 结果: [li.item.active, li.item, li.item]

获取选择器

$('.item').get(0) // 结果: 第一个原生 DOM 元素

插件系统

// 创建自定义方法 cheerio.prototype.myMethod = function() { return this.text().toUpperCase() } // 使用自定义方法 $('.title').myMethod() // 结果: "WELCOME"

🎮 互动演示

试试 Cheerio!

在下方输入 HTML 和选择器,查看实时结果:

点击运行查看结果...

📚 实用示例

网页爬虫示例

const cheerio = require('cheerio'); const axios = require('axios'); async function scrapeWebsite(url) { try { const { data: html } = await axios.get(url); const $ = cheerio.load(html); const results = []; $('.article').each((i, elem) => { const title = $(elem).find('h2').text().trim(); const link = $(elem).find('a').attr('href'); const summary = $(elem).find('.summary').text().trim(); results.push({ title, link, summary }); }); return results; } catch (error) { console.error('爬取失败:', error); } }

数据提取示例

// 提取表格数据 const tableData = []; $('table tr').each((i, row) => { const rowData = []; $(row).find('td').each((j, cell) => { rowData.push($(cell).text()); }); if (rowData.length > 0) { tableData.push(rowData); } }); // 提取图片链接 const imageUrls = []; $('img').each((i, img) => { const src = $(img).attr('src'); if (src) { imageUrls.push(src); } });