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

Tài liệu Cheerio v1.2.0

Cheerio là một thư viện nhanh, linh hoạt và tinh tế để phân tích và thao tác HTML và XML ở phía server. Nó triển khai một tập con các chức năng cốt lõi của jQuery, cung cấp API quen thuộc cho các developer đồng thời được tối ưu hóa cho môi trường server-side.

Tính năng Phiên bản Hiện tại (1.2.0)

Các Phương thức Load Cốt lõi

Phiên bản hiện tại cung cấp nhiều cách mạnh mẽ để load và phân tích các tài liệu 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());
  }
});

Hỗ trợ TypeScript Nâng cao

Phiên bản 1.2.0 bao gồm các định nghĩa TypeScript toàn diện với độ an toàn kiểu được cải thiện:

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

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

Extract API Mới

Một tính năng mới mạnh mẽ để trích xuất dữ liệu từ các tài liệu HTML:

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

Xử lý URL Nâng cao

Hỗ trợ nâng cao cho việc phân giải URL với baseURI:

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

Các Tính năng Chính theo Danh mục

Thao tác DOM

Xử lý Form

// 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 và Styling

// 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');

Data Attribute

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

Di chuyển từ Các Phiên bản Cũ hơn

Từ 0.x lên 1.x

Các Thay đổi Chính cần Chú ý

// 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);

Cải thiện Hiệu suất

Phiên bản 1.2.0 bao gồm các cải tiến hiệu suất đáng kể:

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

Tính năng Nâng cao

Tùy chọn Parser Tùy chỉnh

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

Network Loading với Tùy chọn

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

Thực hành Tốt nhất

  1. Sử dụng TypeScript: Tận dụng các định nghĩa kiểu toàn diện
  2. Stream các tài liệu lớn: Sử dụng streaming API để quản lý bộ nhớ tốt hơn
  3. Tận dụng extract API: Sử dụng phương thức extract mới để trích xuất dữ liệu có cấu trúc
  4. Đặt baseURI: Khi scraping website, hãy đặt baseURI để phân giải URL chính xác

Sự khác biệt giữa Browser và Server

Cheerio được thiết kế để sử dụng phía server và loại bỏ các tính năng jQuery dành riêng cho browser đồng thời thêm các chức năng tối ưu hóa cho server như:

Điều này làm cho Cheerio trở nên lý tưởng cho web scraping, server-side rendering và bất kỳ tác vụ xử lý HTML/XML nào trong môi trường Node.js.