Referensi API Lanjutan Cheerio
Referensi ini mencakup method lanjutan, utilitas, opsi konfigurasi, dan tipe yang meluas melampaui fungsionalitas inti Cheerio.
Method Loading Lanjutan
loadBuffer(buffer, options?)
Memuat HTML/XML dari Buffer dengan deteksi encoding otomatis.
loadBuffer(buffer: Buffer, options?: DecodeStreamOptions): CheerioAPI
Parameter:
buffer- Buffer yang berisi data HTML/XMLoptions- Konfigurasi loading opsional dengan deteksi encoding
Contoh:
import * as cheerio from 'cheerio';
import * as fs from 'fs';
const buffer = fs.readFileSync('index.html');
const $ = cheerio.loadBuffer(buffer);
console.log($('title').text());
Deteksi Encoding:
const $ = cheerio.loadBuffer(buffer, {
encoding: {
defaultEncoding: 'utf8',
transportLayerEncodingLabel: 'windows-1252'
}
});
fromURL(url, options?)
Memuat HTML/XML langsung dari URL dengan HTTP client bawaan.
fromURL(url: string | URL, options?: CheerioRequestOptions): Promise<CheerioAPI>
Parameter:
url- URL yang akan diambiloptions- Opsi request dan parsing
Contoh:
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'
});
Penanganan Error:
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)
Membuat writable stream untuk parsing chunk HTML/XML.
stringStream(
options: CheerioOptions,
cb: (err: Error | null, $: CheerioAPI) => void
): Writable
Contoh:
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);
Ekstraksi Data
.extract(map)
Ekstrak beberapa nilai dari elemen menggunakan pemetaan deklaratif.
extract<M extends ExtractMap>(map: M): ExtractedMap<M>
Ekstraksi Dasar:
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' }
Ekstraksi 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'] }
Ekstraksi Lanjutan dengan Properti Kustom:
const data = $.extract({
links: [{
selector: 'a',
value: 'href' // Extract href attribute instead of text
}],
metadata: {
selector: 'head',
value: {
title: 'title',
description: 'meta[name="description"]'
}
}
});
Fungsi Ekstraksi Kustom:
const data = $.extract({
wordCount: {
selector: 'p',
value: (el, key) => $(el).text().split(' ').length
},
processedContent: {
selector: '.content',
value: (el) => $(el).text().toUpperCase().trim()
}
});
Penanganan Form
.serialize()
Encode elemen form sebagai string berformat URL-encoded.
serialize(): string
Contoh:
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()
Encode elemen form sebagai array dari pasangan name-value.
serializeArray(): Array<{ name: string; value: string }>
Contoh:
const data = $('form').serializeArray();
// Result: [
// { name: 'username', value: 'john_doe' },
// { name: 'email', value: 'john@example.com' },
// { name: 'country', value: 'us' }
// ]
Form Kompleks:
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 Lanjutan
Penggunaan .css() Lanjutan
Setting Berbasis Fungsi:
$('div').css('width', function(index, currentValue) {
return (parseInt(currentValue) || 0) + 10 + 'px';
});
Operasi Massal:
$('p').css({
'font-size': '14px',
'line-height': '1.5',
'margin-bottom': '1em'
});
Getting Berbasis Array:
const styles = $('header').css(['color', 'background-color', 'font-size']);
// Returns object with requested properties
Manipulasi Lanjutan
.wrap() dengan Fungsi
Wrapping Dinamis:
$('img').wrap(function(index) {
const src = $(this).attr('src');
return `<figure class="image-${index}">`;
});
.wrapAll() dan .wrapInner()
Wrap Beberapa Elemen:
$('.related-posts').wrapAll('<section class="sidebar">');
Wrap Konten Dalam:
$('blockquote').wrapInner('<div class="quote-content">');
.unwrap() dengan Selector
Unwrapping Bersyarat:
$('span').unwrap('.temporary-wrapper'); // Only unwrap from .temporary-wrapper
$('em').unwrap(); // Unwrap from any parent
Properti dan Atribut Lanjutan
.prop() Kasus Khusus
Resolusi 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'
Properti 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)
Fitur .data() Lanjutan
Konversi Tipe:
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
// }
Konversi Camel Case:
<div data-user-name="john" data-user-id="123"></div>
$('div').data('userName'); // "john"
$('div').data('userId'); // "123"
Opsi Konfigurasi
Interface CheerioOptions
interface CheerioOptions {
xmlMode?: boolean;
decodeEntities?: boolean;
lowerCaseAttributeNames?: boolean;
recognizeSelfClosing?: boolean;
recognizeCDATA?: boolean;
baseURI?: string;
_useHtmlParser2?: boolean;
}
Mode XML:
const $ = cheerio.load(xmlString, {
xmlMode: true,
recognizeSelfClosing: true
});
Penanganan Entitas HTML:
const $ = cheerio.load(html, {
decodeEntities: false // Keep entities as-is
});
Base URI untuk Resolusi Link:
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;
}
Tipe TypeScript
Tipe Inti
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
}
});
}
Penggunaan Tipe Lanjutan
// 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;
}
Fungsi Utilitas
Method Statis
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'));
Penanganan Error dan Kasus Edge
Degradasi yang Elegan
function safeExtract($: CheerioAPI) {
try {
return $.extract({
title: 'h1',
content: '.content'
});
} catch (error) {
console.warn('Extraction failed:', error);
return { title: undefined, content: undefined };
}
}
Koleksi Kosong
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
Pertimbangan Memori
// 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;
});
Referensi API lanjutan ini mencakup fungsionalitas extended Cheerio melampaui manipulasi DOM dasar, menyediakan tools yang powerful untuk ekstraksi data, penanganan form, streaming, dan operasi yang type-safe.