Cheerio API 레퍼런스
Cheerio는 jQuery 핵심 기능을 빠르고 유연하며 우아하게 서버사이드에서 구현한 라이브러리입니다. Node.js 환경에서 HTML 및 XML 문서를 파싱하고 조작하기 위한 친숙한 jQuery 스타일의 API를 제공합니다.
핵심 로딩 함수
cheerio.load(content, options?)
HTML/XML 콘텐츠를 로드하고 쿼리 및 조작을 위한 CheerioAPI 인스턴스를 반환합니다.
시그니처:
function load(
content: string | AnyNode | AnyNode[] | Buffer,
options?: CheerioOptions,
isDocument?: boolean
): CheerioAPI
매개변수:
| 이름 | 타입 | 기본값 | 설명 |
|---|---|---|---|
content |
string | AnyNode | AnyNode[] | Buffer |
- | 파싱할 HTML/XML 콘텐츠 |
options |
CheerioOptions |
{} |
파서 및 동작 옵션 |
isDocument |
boolean |
true |
콘텐츠를 완전한 문서로 처리할지 여부 |
반환값: CheerioAPI - jQuery와 유사한 메서드를 가진 Cheerio 인스턴스
예제:
import * as cheerio from 'cheerio';
// Basic HTML loading
const $ = cheerio.load('<ul><li>Apple</li><li>Orange</li></ul>');
// With options
const $ = cheerio.load('<xml><item>data</item></xml>', {
xmlMode: true,
decodeEntities: false
});
// Loading from buffer
const buffer = Buffer.from('<div>Hello</div>');
const $ = cheerio.load(buffer);
주의사항:
- XML 문서의 경우 XML 모드를 명시적으로 활성화해야 합니다
- 기본적으로 HTML5 파서 규칙이 적용됩니다 (자기 닫힘 태그 등)
- Buffer 인코딩은 자동으로 감지되지만 명시적 지정이 필요할 수 있습니다
요소 선택
$(selector, context?, root?)
jQuery의 $() 함수와 유사하게 CSS 선택자를 사용해 로드된 문서에서 요소를 선택합니다.
시그니처:
function $(
selector: string | AnyNode | AnyNode[] | Cheerio<AnyNode>,
context?: string | AnyNode | Cheerio<AnyNode>,
root?: string | Document
): Cheerio<Element>
매개변수:
| 이름 | 타입 | 기본값 | 설명 |
|---|---|---|---|
selector |
string | AnyNode | AnyNode[] | Cheerio<AnyNode> |
- | 선택할 CSS 선택자 또는 요소 |
context |
string | AnyNode | Cheerio<AnyNode> |
document |
검색할 컨텍스트 |
root |
string | Document |
- | 컨텍스트의 루트 문서 |
반환값: Cheerio<Element> - 일치하는 요소들의 컬렉션
예제:
// Basic selection
$('li').length; // Number of <li> elements
$('.apple').text(); // Text content of first element with class 'apple'
// With context
$('li', '#fruits').addClass('fruit'); // Find <li> within #fruits
// Complex selectors
$('li:nth-child(2n)').css('color', 'red'); // Every other <li>
$('a[href^="https://"]').attr('target', '_blank'); // External links
속성 조작
.attr(name, value?)
일치하는 요소들의 속성을 가져오거나 설정합니다.
시그니처:
// Get attribute
function attr(name: string): string | undefined;
// Set attribute
function attr(name: string, value: string | null | ((i: number, attr: string) => string | null)): Cheerio<T>;
// Set multiple attributes
function attr(attributes: Record<string, string | null>): Cheerio<T>;
매개변수:
| 이름 | 타입 | 기본값 | 설명 |
|---|---|---|---|
name |
string | Record<string, string | null> |
- | 속성 이름 또는 객체 맵 |
value |
string | null | function |
- | 설정할 값, 제거할 경우 null, 또는 함수 |
반환값: string \| undefined \| Cheerio<T> - 속성 값(getter) 또는 Cheerio 인스턴스(setter)
예제:
// Get attribute
const href = $('a').attr('href'); // Gets href of first <a>
// Set attribute
$('img').attr('alt', 'Description'); // Sets alt text
$('a').attr('href', null); // Removes href attribute
// Multiple attributes
$('input').attr({
type: 'text',
placeholder: 'Enter name',
required: 'required'
});
// Function-based setting
$('img').attr('src', (i, src) => src.replace('http://', 'https://'));
주의사항:
- 속성을
null로 설정하면 완전히 제거됩니다 - Boolean 속성은 존재할 때 이름(
'checked')을 반환하며,true가 아닙니다 - 함수는 인덱스와 현재 값을 매개변수로 받습니다
.prop(name, value?)
DOM 요소의 속성을 가져오거나 설정하며, checked, selected 등 특수 속성을 처리합니다.
시그니처:
// Get property
function prop(name: string): any;
// Set property
function prop(name: string, value: any): Cheerio<T>;
// Set multiple properties
function prop(properties: Record<string, any>): Cheerio<T>;
매개변수:
| 이름 | 타입 | 기본값 | 설명 |
|---|---|---|---|
name |
string | Record<string, any> |
- | 속성 이름 또는 객체 맵 |
value |
any |
- | 설정할 값 |
반환값: any \| Cheerio<T> - 속성 값(getter) 또는 Cheerio 인스턴스(setter)
예제:
// Get property
const isChecked = $('input[type="checkbox"]').prop('checked'); // true/false
// Set property
$('input[type="checkbox"]').prop('checked', true);
$('option').prop('selected', false);
// Special properties
$('a').prop('href'); // Resolved absolute URL
$('div').prop('outerHTML'); // Full HTML including the element
$('div').prop('innerHTML'); // Inner HTML content
.data(key, value?)
HTML5 data-* 속성에서 자동 타입 변환을 통해 데이터 속성을 가져오거나 설정합니다.
시그니처:
// Get all data
function data(): Record<string, unknown>;
// Get specific data
function data(key: string): unknown;
// Set data
function data(key: string, value: unknown): Cheerio<T>;
// Set multiple data
function data(values: Record<string, unknown>): Cheerio<T>;
매개변수:
| 이름 | 타입 | 기본값 | 설명 |
|---|---|---|---|
key |
string | Record<string, unknown> |
- | 데이터 키 또는 객체 맵 |
value |
unknown |
- | 설정할 값 |
반환값: unknown \| Record<string, unknown> \| Cheerio<T> - 데이터 값 또는 Cheerio 인스턴스
예제:
// HTML: <div data-user-id="123" data-active="true">
const userId = $('.user').data('userId'); // 123 (number)
const isActive = $('.user').data('active'); // true (boolean)
// Set data
$('.user').data('lastSeen', new Date());
$('.user').data({
role: 'admin',
permissions: ['read', 'write']
});
// Camel case conversion
$('<div data-foo-bar="test">').data('fooBar'); // "test"
주의사항:
- 데이터 속성은 자동으로 파싱됩니다 (JSON, 숫자, boolean)
- 카멜케이스 키는 하이픈 구분 데이터 속성에 매핑됩니다
.data()로 설정된 데이터는 실제 HTML 속성을 업데이트하지 않습니다
콘텐츠 조작
.text(value?)
요소의 텍스트 콘텐츠를 가져오거나 설정하며, 모든 HTML 태그를 제거합니다.
시그니처:
// Get text
function text(): string;
// Set text
function text(value: string | number | ((i: number, text: string) => string | number)): Cheerio<T>;
매개변수:
| 이름 | 타입 | 기본값 | 설명 |
|---|---|---|---|
value |
string | number | function |
- | 설정할 텍스트 콘텐츠 또는 함수 |
반환값: string \| Cheerio<T> - 텍스트 콘텐츠(getter) 또는 Cheerio 인스턴스(setter)
예제:
// Get text content
const title = $('h1').text(); // "Welcome to My Site"
// Set text (HTML-safe)
$('h1').text('New <Title>'); // Displays: "New <Title>" (not rendered as HTML)
// Function-based setting
$('li').text((i, currentText) => `${i + 1}. ${currentText}`);
.html(value?)
요소의 내부 HTML 콘텐츠를 가져오거나 설정합니다.
시그니처:
// Get HTML
function html(): string | null;
// Set HTML
function html(value: string | ((i: number, html: string) => string)): Cheerio<T>;
매개변수:
| 이름 | 타입 | 기본값 | 설명 |
|---|---|---|---|
value |
string | function |
- | 설정할 HTML 콘텐츠 또는 함수 |
반환값: string \| null \| Cheerio<T> - HTML 콘텐츠(getter) 또는 Cheerio 인스턴스(setter)
예제:
// Get HTML
const content = $('.container').html(); // "<p>Hello <strong>world</strong></p>"
// Set HTML
$('.container').html('<p>New content</p>');
// Function-based setting
$('div').html((i, oldHtml) => `<span>Item ${i}</span>${oldHtml}`);
주의사항:
.html()은 내부 HTML을 반환하므로, 완전한 요소를 얻으려면.prop('outerHTML')을 사용하세요- HTML 설정 시 기존 모든 콘텐츠를 덮어씁니다
- HTML은 sanitize되지 않으므로 사용자 입력에 주의하세요
.val(value?)
폼 요소(input, select, textarea)의 값을 가져오거나 설정합니다.
시그니처:
// Get value
function val(): string | string[] | undefined;
// Set value
function val(value: string | string[]): Cheerio<T>;
매개변수:
| 이름 | 타입 | 기본값 | 설명 |
|---|---|---|---|
value |
string | string[] |
- | 설정할 값 (다중 선택의 경우 배열) |
반환값: string \| string[] \| undefined \| Cheerio<T> - 폼 값 또는 Cheerio 인스턴스
예제:
// Get values
const inputValue = $('input[name="email"]').val(); // "user@example.com"
const selectedOptions = $('select[multiple]').val(); // ["option1", "option2"]
// Set values
$('input[type="text"]').val('New value');
$('select[multiple]').val(['option1', 'option3']); // Selects multiple options
$('textarea').val('Long text content...');
DOM 조작
.append(content)
각 일치하는 요소의 마지막 자식으로 콘텐츠를 삽입합니다.
시그니처:
function append(
...contents: (
| string
| AnyNode
| AnyNode[]
| Cheerio<AnyNode>
| ((i: number, html: string) => string | AnyNode | Cheerio<AnyNode>)
)[]
): Cheerio<T>;
매개변수:
| 이름 | 타입 | 기본값 | 설명 |
|---|---|---|---|
contents |
string | AnyNode | Cheerio | function |
- | 추가할 콘텐츠 |
반환값: Cheerio<T> - 원래 Cheerio 인스턴스
예제:
// Append HTML string
$('ul').append('<li>New item</li>');
// Append multiple items
$('ul').append('<li>Item 1</li>', '<li>Item 2</li>');
// Append Cheerio object
const $newLi = $('<li>').text('Dynamic item');
$('ul').append($newLi);
// Function-based appending
$('div').append((i, html) => `<p>Section ${i + 1}</p>`);
.remove(selector?)
DOM에서 일치하는 요소들을 제거합니다.
시그니처:
function remove(selector?: string): Cheerio<T>;
매개변수:
| 이름 | 타입 | 기본값 | 설명 |
|---|---|---|---|
selector |
string |
- | 제거를 필터링할 선택자(선택사항) |
반환값: Cheerio<T> - 제거된 요소들
예제:
// Remove all matched elements
$('.obsolete').remove();
// Remove with filtering
$('li').remove(':contains("delete")'); // Remove <li> containing "delete"
// Chain after removal
$('p').remove().appendTo('.archive'); // Move to archive
CSS 및 스타일링
.css(property, value?)
요소의 CSS 스타일을 가져오거나 설정합니다.
시그니처:
// Get style
function css(property: string): string | undefined;
// Set style
function css(property: string, value: string | ((i: number, style: string) => string)): Cheerio<T>;
// Set multiple styles
function css(properties: Record<string, string>): Cheerio<T>;
// Get multiple styles
function css(properties: string[]): Record<string, string>;
매개변수:
| 이름 | 타입 | 기본값 | 설명 |
|---|---|---|---|
property |
string | string[] | Record<string, string> |
- | CSS 속성명, 배열, 또는 객체 |
value |
string | function |
- | 설정할 CSS 값 또는 함수 |
반환값: string \| Record<string, string> \| Cheerio<T> - CSS 값(들) 또는 Cheerio 인스턴스
예제:
// Get computed style
const color = $('.highlight').css('color'); // "red"
// Set single style
$('.box').css('background-color', 'blue');
// Set multiple styles
$('.card').css({
'border-radius': '8px',
'box-shadow': '0 2px 4px rgba(0,0,0,0.1)',
padding: '16px'
});
// Function-based setting
$('div').css('width', (i, width) => `${parseInt(width) + 10}px`);
.addClass(className)
일치하는 요소들에 CSS 클래스를 추가합니다.
시그니처:
function addClass(
className: string | ((i: number, currentClass: string) => string)
): Cheerio<T>;
매개변수:
| 이름 | 타입 | 기본값 | 설명 |
|---|---|---|---|
className |
string | function |
- | 공백으로 구분된 클래스명 또는 함수 |
반환값: Cheerio<T> - 메서드 체이닝을 위한 Cheerio 인스턴스
예제:
// Add single class
$('.item').addClass('active');
// Add multiple classes
$('.card').addClass('highlighted featured');
// Function-based adding
$('li').addClass((i, currentClass) => {
return i % 2 === 0 ? 'even' : 'odd';
});
.removeClass(className?)
일치하는 요소들에서 CSS 클래스를 제거합니다.
시그니처:
function removeClass(
className?: string | ((i: number, currentClass: string) => string)
): Cheerio<T>;
매개변수:
| 이름 | 타입 | 기본값 | 설명 |
|---|---|---|---|
className |
string | function |
- | 제거할 클래스 또는 함수 (생략 시 모든 클래스 제거) |
반환값: Cheerio<T> - 메서드 체이닝을 위한 Cheerio 인스턴스
예제:
// Remove specific class
$('.item').removeClass('active');
// Remove multiple classes
$('.card').removeClass('highlighted featured');
// Remove all classes
$('.temp').removeClass();
// Function-based removal
$('div').removeClass((i, currentClass) => {
return currentClass.includes('temp-') ? currentClass : '';
});
.hasClass(className)
일치하는 요소 중 지정된 CSS 클래스를 가진 요소가 있는지 확인합니다.
시그니처:
function hasClass(className: string): boolean;
매개변수:
| 이름 | 타입 | 기본값 | 설명 |
|---|---|---|---|
className |
string |
- | 확인할 클래스명 |
반환값: boolean - 어떤 요소라도 해당 클래스를 가지고 있으면 true
예제:
// Check for class
if ($('.nav-item').hasClass('active')) {
console.log('Found active navigation item');
}
// Conditional logic
$('.button').each(function() {
if ($(this).hasClass('primary')) {
$(this).css('font-weight', 'bold');
}
});
탐색 및 필터링
.find(selector)
선택자와 일치하는 후손 요소를 검색합니다.
시그니처:
function find<T extends AnyNode>(selector: string): Cheerio<T>;
매개변수:
| 이름 | 타입 | 기본값 | 설명 |
|---|---|---|---|
selector |
string |
- | 검색할 CSS 선택자 |
반환값: Cheerio<T> - 찾은 후손 요소들의 컬렉션
예제:
// Find descendants
const links = $('.nav').find('a'); // All <a> tags inside .nav
// Complex selectors
const activeLinks = $('.menu').find('li.active a[href]');
// Chain with other methods
$('.article').find('img').attr('loading', 'lazy');
.each(callback)
일치하는 요소들을 반복하며 각각에 대해 callback을 실행합니다.
시그니처:
function each(
callback: (this: T, i: number, el: T) => void | false
): Cheerio<T>;
매개변수:
| 이름 | 타입 | 기본값 | 설명 |
|---|---|---|---|
callback |
function |
- | 각 요소에 대해 실행할 함수 |
반환값: Cheerio<T> - 원래 Cheerio 인스턴스
예제:
// Basic iteration
$('li').each(function(i, el) {
console.log(`Item ${i}: ${$(el).text()}`);
});
// Early termination
$('.item').each(function(i) {
if ($(this).hasClass('stop')) return false; // Break loop
$(this).addClass(`item-${i}`);
});
// Arrow function (note: `this` context differs)
$('img').each((i, img) => {
$(img).attr('alt', `Image ${i + 1}`);
});
주의사항:
- callback에서
false를 반환하면 루프를 조기 중단합니다 - 화살표 함수는
this를 현재 요소에 바인딩하지 않습니다 - 인덱스 매개변수는 0부터 시작합니다
폼 처리
.serialize()
폼 요소들을 URL-encoded 쿼리 문자열로 직렬화합니다.
시그니처:
function serialize(): string;
반환값: string - URL-encoded 폼 데이터
예제:
// Serialize entire form
const formData = $('form').serialize();
// "name=John&email=john%40example.com&subscribe=on"
// Serialize specific inputs
const inputData = $('input[type="text"], select').serialize();
.serializeArray()
폼 요소들을 name-value 객체의 배열로 직렬화합니다.
시그니처:
function serializeArray(): Array<{ name: string; value: string }>;
반환값: Array<{ name: string; value: string }> - 폼 데이터 객체의 배열
예제:
// Get structured form data
const formArray = $('form').serializeArray();
// [{ name: 'email', value: 'user@example.com' }, { name: 'subscribe', value: 'on' }]
// Convert to object
const formObject = {};
$('form').serializeArray().forEach(item => {
formObject[item.name] = item.value;
});
주의사항:
- 성공적인 폼 컨트롤만 직렬화됩니다
- 비활성화된 요소는 무시됩니다
- 체크박스/라디오는 체크된 상태여야 포함됩니다
- 파일 입력은 파일 내용이 아닌 파일명을 반환합니다