Tài liệu tham khảo API nâng cao của Cheerio
Tài liệu tham khảo này bao gồm các phương thức nâng cao, tiện ích, tùy chọn cấu hình và các kiểu dữ liệu mở rộng ngoài chức năng cốt lõi của Cheerio.
Phương thức tải nâng cao
loadBuffer(buffer, options?)
Tải HTML/XML từ Buffer với tự động phát hiện mã hóa.
loadBuffer(buffer: Buffer, options?: DecodeStreamOptions): CheerioAPI
Tham số:
buffer- Buffer chứa dữ liệu HTML/XMLoptions- Cấu hình tải tùy chọn với phát hiện mã hóa
Ví dụ:
import * as cheerio from 'cheerio';
import * as fs from 'fs';
const buffer = fs.readFileSync('index.html');
const $ = cheerio.loadBuffer(buffer);
console.log($('title').text());
Phát hiện mã hóa:
const $ = cheerio.loadBuffer(buffer, {
encoding: {
defaultEncoding: 'utf8',
transportLayerEncodingLabel: 'windows-1252'
}
});
fromURL(url, options?)
Tải HTML/XML trực tiếp từ URL với HTTP client tích hợp sẵn.
fromURL(url: string | URL, options?: CheerioRequestOptions): Promise<CheerioAPI>
Tham số:
url- URL cần tảioptions- Tùy chọn yêu cầu và phân tích cú pháp
Ví dụ:
const $ = await cheerio.fromURL('https://example.com');
console.log($('h1').text());
// With custom headers and options
const $page = await cheerio.fromURL('https://api.example.com/data', {
requestOptions: {
headers: { 'User-Agent': 'MyBot/1.0' },
method: 'GET'
},
xmlMode: false,
baseURI: 'https://api.example.com'
});
Xử lý lỗi:
try {
const $ = await cheerio.fromURL('https://invalid-url.com');
} catch (error) {
if (error instanceof undici.errors.ResponseError) {
console.log(`HTTP ${error.statusCode}: Request failed`);
}
}
stringStream(options, callback)
Tạo một stream có thể ghi để phân tích cú pháp các đoạn HTML/XML.
stringStream(
options: CheerioOptions,
cb: (err: Error | null, $: CheerioAPI) => void
): Writable
Ví dụ:
import * as fs from 'fs';
const writeStream = cheerio.stringStream({}, (err, $) => {
if (err) throw err;
console.log($('title').text());
});
fs.createReadStream('large-file.html', { encoding: 'utf8' })
.pipe(writeStream);
Trích xuất dữ liệu
.extract(map)
Trích xuất nhiều giá trị từ các phần tử sử dụng ánh xạ khai báo.
extract<M extends ExtractMap>(map: M): ExtractedMap<M>
Trích xuất cơ bản:
const $ = cheerio.load(`
<div>
<h1 class="title">Welcome</h1>
<p class="content">Hello world</p>
<a href="/page" class="link">Click here</a>
</div>
`);
const data = $.extract({
title: 'h1.title',
content: '.content',
link: '.link'
});
// Result: { title: 'Welcome', content: 'Hello world', link: 'Click here' }
Trích xuất mảng:
const $ = cheerio.load(`
<ul>
<li class="item">Item 1</li>
<li class="item">Item 2</li>
<li class="item">Item 3</li>
</ul>
`);
const data = $.extract({
items: ['.item'] // Array syntax for multiple elements
});
// Result: { items: ['Item 1', 'Item 2', 'Item 3'] }
Trích xuất nâng cao với thuộc tính tùy chỉnh:
const data = $.extract({
links: [{
selector: 'a',
value: 'href' // Extract href attribute instead of text
}],
metadata: {
selector: 'head',
value: {
title: 'title',
description: 'meta[name="description"]'
}
}
});
Hàm trích xuất tùy chỉnh:
const data = $.extract({
wordCount: {
selector: 'p',
value: (el, key) => $(el).text().split(' ').length
},
processedContent: {
selector: '.content',
value: (el) => $(el).text().toUpperCase().trim()
}
});
Xử lý form
.serialize()
Mã hóa các phần tử form thành chuỗi mã hóa URL.
serialize(): string
Ví dụ:
const $ = cheerio.load(`
<form>
<input name="username" value="john_doe" />
<input name="email" value="john@example.com" />
<select name="country">
<option value="us" selected>United States</option>
<option value="ca">Canada</option>
</select>
</form>
`);
const serialized = $('form').serialize();
// Result: "username=john_doe&email=john%40example.com&country=us"
.serializeArray()
Mã hóa các phần tử form thành mảng các cặp tên-giá trị.
serializeArray(): Array<{ name: string; value: string }>
Ví dụ:
const data = $('form').serializeArray();
// Result: [
// { name: 'username', value: 'john_doe' },
// { name: 'email', value: 'john@example.com' },
// { name: 'country', value: 'us' }
// ]
Form phức tạp:
const $ = cheerio.load(`
<form>
<input name="tags" value="javascript" type="checkbox" checked />
<input name="tags" value="nodejs" type="checkbox" checked />
<textarea name="comment">Great article!</textarea>
</form>
`);
const formData = $('form').serializeArray();
// Handles multiple values, textareas, and checkboxes automatically
Phương thức CSS nâng cao
Cách sử dụng nâng cao của .css()
Thiết lập dựa trên hàm:
$('div').css('width', function(index, currentValue) {
return (parseInt(currentValue) || 0) + 10 + 'px';
});
Thao tác hàng loạt:
$('p').css({
'font-size': '14px',
'line-height': '1.5',
'margin-bottom': '1em'
});
Lấy dựa trên mảng:
const styles = $('header').css(['color', 'background-color', 'font-size']);
// Returns object with requested properties
Thao tác nâng cao
.wrap() với hàm
Bao bọc động:
$('img').wrap(function(index) {
const src = $(this).attr('src');
return `<figure class="image-${index}">`;
});
.wrapAll() và .wrapInner()
Bao bọc nhiều phần tử:
$('.related-posts').wrapAll('<section class="sidebar">');
Bao bọc nội dung bên trong:
$('blockquote').wrapInner('<div class="quote-content">');
.unwrap() với bộ chọn
Bỏ bao bọc có điều kiện:
$('span').unwrap('.temporary-wrapper'); // Only unwrap from .temporary-wrapper
$('em').unwrap(); // Unwrap from any parent
Thuộc tính và attribute nâng cao
Trường hợp đặc biệt của .prop()
Giải quyết URL:
const $ = cheerio.load('<a href="page.html">Link</a>', {
baseURI: 'https://example.com/blog/'
});
console.log($('a').prop('href')); // 'https://example.com/blog/page.html'
Thuộc tính DOM:
const $input = $('<input type="checkbox" checked>');
console.log($input.prop('checked')); // true
console.log($input.attr('checked')); // 'checked'
$input.prop('checked', false);
console.log($input.attr('checked')); // undefined (removed)
Tính năng nâng cao của .data()
Ép kiểu:
const $ = cheerio.load(`
<div
data-count="42"
data-active="true"
data-config='{"theme": "dark"}'
data-list="[1,2,3]"
data-empty="null"
></div>
`);
const data = $('div').data();
// Result: {
// count: 42, // number
// active: true, // boolean
// config: {theme: "dark"}, // object
// list: [1,2,3], // array
// empty: null // null
// }
Chuyển đổi camelCase:
<div data-user-name="john" data-user-id="123"></div>
$('div').data('userName'); // "john"
$('div').data('userId'); // "123"
Tùy chọn cấu hình
Interface CheerioOptions
interface CheerioOptions {
xmlMode?: boolean;
decodeEntities?: boolean;
lowerCaseAttributeNames?: boolean;
recognizeSelfClosing?: boolean;
recognizeCDATA?: boolean;
baseURI?: string;
_useHtmlParser2?: boolean;
}
Chế độ XML:
const $ = cheerio.load(xmlString, {
xmlMode: true,
recognizeSelfClosing: true
});
Xử lý HTML Entity:
const $ = cheerio.load(html, {
decodeEntities: false // Keep entities as-is
});
URI cơ sở cho giải quyết liên kết:
const $ = cheerio.load(html, {
baseURI: 'https://example.com/articles/'
});
$('a').each((i, el) => {
console.log($(el).prop('href')); // Resolves relative URLs
});
HTMLParser2Options
interface HTMLParser2Options {
lowerCaseAttributeNames?: boolean;
recognizeSelfClosing?: boolean;
recognizeCDATA?: boolean;
xmlMode?: boolean;
decodeEntities?: boolean;
}
Kiểu dữ liệu TypeScript
Kiểu cốt lõi
import type {
CheerioAPI,
Cheerio,
Element,
AnyNode,
CheerioOptions
} from 'cheerio';
// Custom element processing
function processElements(elements: Cheerio<Element>) {
elements.each((index, element) => {
if (element.tagName === 'img') {
// Process images
}
});
}
Cách sử dụng kiểu nâng cao
// Type-safe extraction
interface ArticleData {
title: string;
author: string;
publishDate: string;
tags: string[];
}
function extractArticle($: CheerioAPI): ArticleData {
return $.extract({
title: 'h1',
author: '.author',
publishDate: '.date',
tags: ['.tag']
}) as ArticleData;
}
Hàm tiện ích
Phương thức tĩnh
import { contains, merge } from 'cheerio';
// Check if one element contains another
const isContained = contains(parentElement, childElement);
// Merge multiple Cheerio objects
const combined = merge($('.class1'), $('.class2'));
Xử lý lỗi và trường hợp đặc biệt
Suy giảm một cách duyên dáng
function safeExtract($: CheerioAPI) {
try {
return $.extract({
title: 'h1',
content: '.content'
});
} catch (error) {
console.warn('Extraction failed:', error);
return { title: undefined, content: undefined };
}
}
Collection rỗng
const $empty = $('.nonexistent');
console.log($empty.length); // 0
console.log($empty.text()); // ""
console.log($empty.attr('class')); // undefined
// Chaining still works
$empty.addClass('test').removeClass('other'); // No-op, returns $empty
Cân nhắc bộ nhớ
// For large documents, consider streaming
const stream = cheerio.stringStream({ xmlMode: true }, (err, $) => {
if (err) throw err;
// Process document
const data = $.extract({ /* ... */ });
// Clean up if needed
$ = null;
});
Tài liệu tham khảo API nâng cao này bao gồm chức năng mở rộng của Cheerio ngoài thao tác DOM cơ bản, cung cấp các công cụ mạnh mẽ cho trích xuất dữ liệu, xử lý form, streaming và các thao tác type-safe.