คู่มืออ้างอิง API ขั้นสูงของ Cheerio
คู่มืออ้างอิงนี้ครอบคลุม method ขั้นสูง, ยูทิลิตี้, ตัวเลือกการกำหนดค่า และ type ที่ขยายเกินฟังก์ชันหลักของ Cheerio
method การโหลดขั้นสูง
loadBuffer(buffer, options?)
โหลด HTML/XML จาก Buffer พร้อมการตรวจจับ encoding อัตโนมัติ
loadBuffer(buffer: Buffer, options?: DecodeStreamOptions): CheerioAPI
พารามิเตอร์:
buffer- Buffer ที่มีข้อมูล HTML/XMLoptions- การกำหนดค่าการโหลดเสริมพร้อมการตรวจจับ encoding
ตัวอย่าง:
import * as cheerio from 'cheerio';
import * as fs from 'fs';
const buffer = fs.readFileSync('index.html');
const $ = cheerio.loadBuffer(buffer);
console.log($('title').text());
การตรวจจับ Encoding:
const $ = cheerio.loadBuffer(buffer, {
encoding: {
defaultEncoding: 'utf8',
transportLayerEncodingLabel: 'windows-1252'
}
});
fromURL(url, options?)
โหลด HTML/XML โดยตรงจาก URL พร้อม HTTP client ในตัว
fromURL(url: string | URL, options?: CheerioRequestOptions): Promise<CheerioAPI>
พารามิเตอร์:
url- URL ที่จะดึงข้อมูลoptions- ตัวเลือกสำหรับ request และการแยกวิเคราะห์
ตัวอย่าง:
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'
});
การจัดการข้อผิดพลาด:
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)
สร้าง writable stream สำหรับแยกวิเคราะห์ HTML/XML เป็นชิ้นๆ
stringStream(
options: CheerioOptions,
cb: (err: Error | null, $: CheerioAPI) => void
): Writable
ตัวอย่าง:
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);
การแยกข้อมูล
.extract(map)
แยกค่าหลายค่าจาก element โดยใช้การแมปแบบประกาศ
extract<M extends ExtractMap>(map: M): ExtractedMap<M>
การแยกข้อมูลพื้นฐาน:
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' }
การแยกข้อมูลแบบ Array:
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'] }
การแยกข้อมูลขั้นสูงพร้อม Property กำหนดเอง:
const data = $.extract({
links: [{
selector: 'a',
value: 'href' // Extract href attribute instead of text
}],
metadata: {
selector: 'head',
value: {
title: 'title',
description: 'meta[name="description"]'
}
}
});
ฟังก์ชันแยกข้อมูลกำหนดเอง:
const data = $.extract({
wordCount: {
selector: 'p',
value: (el, key) => $(el).text().split(' ').length
},
processedContent: {
selector: '.content',
value: (el) => $(el).text().toUpperCase().trim()
}
});
การจัดการฟอร์ม
.serialize()
เข้ารหัส element ของฟอร์มเป็น string แบบ URL-encoded
serialize(): string
ตัวอย่าง:
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()
เข้ารหัส element ของฟอร์มเป็น array ของคู่ name-value
serializeArray(): Array<{ name: string; value: string }>
ตัวอย่าง:
const data = $('form').serializeArray();
// Result: [
// { name: 'username', value: 'john_doe' },
// { name: 'email', value: 'john@example.com' },
// { name: 'country', value: 'us' }
// ]
ฟอร์มที่ซับซ้อน:
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
method CSS ขั้นสูง
การใช้งาน .css() ขั้นสูง
การตั้งค่าแบบใช้ฟังก์ชัน:
$('div').css('width', function(index, currentValue) {
return (parseInt(currentValue) || 0) + 10 + 'px';
});
การดำเนินการแบบกลุ่ม:
$('p').css({
'font-size': '14px',
'line-height': '1.5',
'margin-bottom': '1em'
});
การรับค่าแบบ Array:
const styles = $('header').css(['color', 'background-color', 'font-size']);
// Returns object with requested properties
การจัดการขั้นสูง
.wrap() พร้อมฟังก์ชัน
การห่อแบบไดนามิก:
$('img').wrap(function(index) {
const src = $(this).attr('src');
return `<figure class="image-${index}">`;
});
.wrapAll() และ .wrapInner()
ห่อ Element หลายตัว:
$('.related-posts').wrapAll('<section class="sidebar">');
ห่อเนื้อหาภายใน:
$('blockquote').wrapInner('<div class="quote-content">');
.unwrap() พร้อม Selector
การคลี่ห่อแบบมีเงื่อนไข:
$('span').unwrap('.temporary-wrapper'); // Only unwrap from .temporary-wrapper
$('em').unwrap(); // Unwrap from any parent
Property และ Attribute ขั้นสูง
.prop() กรณีพิเศษ
การแก้ไข 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'
Property ของ 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)
.data() ฟีเจอร์ขั้นสูง
การแปลง Type:
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
// }
การแปลงเป็น Camel Case:
<div data-user-name="john" data-user-id="123"></div>
$('div').data('userName'); // "john"
$('div').data('userId'); // "123"
ตัวเลือกการกำหนดค่า
อินเทอร์เฟซ CheerioOptions
interface CheerioOptions {
xmlMode?: boolean;
decodeEntities?: boolean;
lowerCaseAttributeNames?: boolean;
recognizeSelfClosing?: boolean;
recognizeCDATA?: boolean;
baseURI?: string;
_useHtmlParser2?: boolean;
}
โหมด XML:
const $ = cheerio.load(xmlString, {
xmlMode: true,
recognizeSelfClosing: true
});
การจัดการ HTML Entity:
const $ = cheerio.load(html, {
decodeEntities: false // Keep entities as-is
});
Base URI สำหรับการแก้ไขลิงค์:
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;
}
Type ของ TypeScript
Type หลัก
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
}
});
}
การใช้งาน Type ขั้นสูง
// 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;
}
ฟังก์ชันยูทิลิตี้
Method แบบ Static
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'));
การจัดการข้อผิดพลาดและกรณีพิเศษ
การลดทอนอย่างสง่างาม
function safeExtract($: CheerioAPI) {
try {
return $.extract({
title: 'h1',
content: '.content'
});
} catch (error) {
console.warn('Extraction failed:', error);
return { title: undefined, content: undefined };
}
}
Collection ที่ว่างเปล่า
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
ข้อพิจารณาเรื่องหน่วยความจำ
// 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;
});
คู่มืออ้างอิง API ขั้นสูงนี้ครอบคลุมฟังก์ชันเสริมของ Cheerio นอกเหนือจากการจัดการ DOM พื้นฐาน โดยให้เครื่องมืออันทรงพลังสำหรับการแยกข้อมูล, การจัดการฟอร์ม, streaming และการทำงานแบบ type-safe