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

Cheerio 上級API リファレンス

このリファレンスでは、Cheerioのコア機能を超えた上級メソッド、ユーティリティ、設定オプション、型について説明します。

上級読み込みメソッド

loadBuffer(buffer, options?)

自動エンコーディング検出機能付きでBufferからHTML/XMLを読み込みます。

loadBuffer(buffer: Buffer, options?: DecodeStreamOptions): CheerioAPI

パラメータ:

例:

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>

パラメータ:

例:

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の拡張機能について説明し、データ抽出、フォーム処理、ストリーミング、型安全な操作のための強力なツールを提供しています。