DE EN ES FR ID JA KO PT RU TH VI ZH

Cheerio v1.2.0 문서

Cheerio는 서버 측에서 HTML과 XML을 파싱하고 조작하기 위한 빠르고 유연하며 우아한 라이브러리입니다. jQuery의 핵심 기능 중 일부를 구현하여 개발자들에게 친숙한 API를 제공하면서도 서버 측 환경에 최적화되어 있습니다.

현재 버전(1.2.0) 기능

핵심 로딩 메소드

현재 버전은 HTML/XML 문서를 로드하고 파싱하는 여러 가지 강력한 방법을 제공합니다:

import * as cheerio from 'cheerio';

// Basic loading from string
const $ = cheerio.load('<h2 class="title">Hello world</h2>');

// Loading from buffer with encoding detection
const buffer = fs.readFileSync('index.html');
const $ = cheerio.loadBuffer(buffer);

// Loading from URL with automatic encoding detection
const $ = await cheerio.fromURL('https://example.com');

// Stream-based loading for large documents
const stream = cheerio.stringStream({}, (err, $) => {
  if (!err) {
    console.log($('h1').text());
  }
});

향상된 TypeScript 지원

버전 1.2.0에는 개선된 타입 안전성과 함께 포괄적인 TypeScript 정의가 포함되어 있습니다:

import { CheerioAPI, Cheerio, Element } from 'cheerio';

// Strongly typed element selection
const $: CheerioAPI = cheerio.load(html);
const elements: Cheerio<Element> = $('.my-class');

새로운 Extract API

HTML 문서에서 데이터를 추출하기 위한 강력한 새 기능:

const data = $root.extract({
  title: 'h1',
  links: [{ selector: 'a', value: 'href' }],
  metadata: {
    selector: '.meta',
    value: {
      author: '.author',
      date: '.date'
    }
  }
});

고급 URL 처리

baseURI를 사용한 향상된 URL 해석 지원:

const $ = cheerio.load(html, { 
  baseURI: 'https://example.com/page/' 
});

// Automatically resolves relative URLs
$('a').prop('href'); // Returns absolute URL
$('img').prop('src'); // Returns absolute URL

카테고리별 주요 기능

DOM 조작

폼 처리

// Serialize forms to URL-encoded strings
$('form').serialize(); // 'name=value&email=test@example.com'

// Get form data as structured arrays
$('form').serializeArray();
// [{ name: 'username', value: 'john' }, ...]

CSS 및 스타일링

// Get/set CSS properties
$('.element').css('color', 'red');
$('.element').css(['margin', 'padding']); // Get multiple properties

// Class manipulation
$('.item').addClass('active selected');
$('.item').removeClass('old-class');
$('.item').toggleClass('visible');

데이터 속성

// HTML5 data-* attribute support with automatic type coercion
$('.widget').data('config'); // Parses JSON automatically
$('.widget').data('count', 42); // Set data programmatically

이전 버전에서 마이그레이션

0.x에서 1.x로

주의해야 할 주요 변경사항

// Old way (0.x) - still works but discouraged
const cheerio = require('cheerio');
const $ = cheerio.load(html);

// New way (1.x) - recommended
import * as cheerio from 'cheerio';
const $ = cheerio.load(html);

성능 개선

버전 1.2.0에는 상당한 성능 향상이 포함되어 있습니다:

// Stream processing for large files
const stream = cheerio.decodeStream({
  encoding: { defaultEncoding: 'utf8' }
}, (err, $) => {
  // Process document as it streams
});

고급 기능

사용자 정의 Parser 옵션

const $ = cheerio.load(html, {
  xmlMode: true,        // Parse as XML
  decodeEntities: false, // Don't decode HTML entities
  scriptingEnabled: false // Disable script tag processing
});

옵션을 사용한 네트워크 로딩

const $ = await cheerio.fromURL('https://api.example.com/data', {
  requestOptions: {
    headers: { 'User-Agent': 'MyBot/1.0' }
  },
  encoding: { defaultEncoding: 'utf8' }
});

모범 사례

  1. TypeScript 사용: 포괄적인 타입 정의를 활용하세요
  2. 대용량 문서 스트리밍: 더 나은 메모리 관리를 위해 스트리밍 API를 사용하세요
  3. extract API 활용: 구조화된 데이터 추출을 위해 새로운 extract 메소드를 사용하세요
  4. baseURI 설정: 웹사이트를 스크래핑할 때 적절한 URL 해석을 위해 baseURI를 설정하세요

브라우저와 서버의 차이점

Cheerio는 서버 측 사용을 위해 설계되었으며 브라우저 특정 jQuery 기능을 제거하는 동시에 다음과 같은 서버 최적화 기능을 추가합니다:

이는 Cheerio를 Node.js 환경에서 웹 스크래핑, 서버 측 렌더링 및 모든 HTML/XML 처리 작업에 이상적으로 만듭니다.