Cheerio 고급 API 참조
이 참조는 Cheerio의 핵심 기능을 넘어서는 고급 메소드, 유틸리티, 설정 옵션 및 타입을 다룹니다.
고급 로딩 메소드
loadBuffer(buffer, options?)
자동 인코딩 감지를 통해 Buffer에서 HTML/XML을 로드합니다.
loadBuffer(buffer: Buffer, options?: DecodeStreamOptions): CheerioAPI
매개변수:
buffer- HTML/XML 데이터가 포함된 Bufferoptions- 인코딩 감지를 포함한 선택적 로딩 설정
예제:
import * as cheerio from 'cheerio';
import * as fs from 'fs';
const buffer = fs.readFileSync('index.html');
const $ = cheerio.loadBuffer(buffer);
console.log($('title').text());
인코딩 감지:
const $ = cheerio.loadBuffer(buffer, {
encoding: {
defaultEncoding: 'utf8',
transportLayerEncodingLabel: 'windows-1252'
}
});
fromURL(url, options?)
내장된 HTTP 클라이언트를 사용하여 URL에서 직접 HTML/XML을 로드합니다.
fromURL(url: string | URL, options?: CheerioRequestOptions): Promise<CheerioAPI>
매개변수:
url- 가져올 URLoptions- 요청 및 파싱 옵션
예제:
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)
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)
선언적 매핑을 사용하여 요소에서 여러 값을 추출합니다.
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' }
배열 추출:
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'] }
커스텀 속성을 사용한 고급 추출:
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()
폼 요소를 URL 인코딩된 문자열로 인코딩합니다.
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()
폼 요소를 이름-값 쌍의 배열로 인코딩합니다.
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
고급 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'
});
배열 기반 가져오기:
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()
여러 요소 래핑:
$('.related-posts').wrapAll('<section class="sidebar">');
내부 콘텐츠 래핑:
$('blockquote').wrapInner('<div class="quote-content">');
선택자와 함께 사용하는 .unwrap()
조건부 언래핑:
$('span').unwrap('.temporary-wrapper'); // Only unwrap from .temporary-wrapper
$('em').unwrap(); // Unwrap from any parent
속성 및 특성 고급
.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'
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() 고급 기능
타입 강제 변환:
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
// }
카멜 케이스 변환:
<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 엔티티 처리:
const $ = cheerio.load(html, {
decodeEntities: false // Keep entities as-is
});
링크 해석을 위한 기본 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;
}
TypeScript 타입
핵심 타입
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-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;
}
유틸리티 함수
정적 메소드
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 };
}
}
빈 컬렉션
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 참조는 기본적인 DOM 조작을 넘어서는 Cheerio의 확장된 기능을 다루며, 데이터 추출, 폼 처리, 스트리밍 및 타입 안전 작업을 위한 강력한 도구를 제공합니다.