Cheerio FAQ
他のHTMLパーシングライブラリと比較してCheerioはどの程度高速ですか?
Cheerioは速度と効率性を重視して設計されています。domhandlerベースの軽量DOM modelを使用しており、JSDOMなどの完全なブラウザDOM実装よりも大幅に高速です。ブラウザベースのソリューションとは異なり、CheerioはDOMの不整合やブラウザのオーバーヘッドを排除し、極めて高速なパースと操作処理を実現します。
import * as cheerio from 'cheerio';
// Fast parsing - no browser overhead
const $ = cheerio.load('<div>Large HTML document...</div>');
// Efficient manipulation
$('div').addClass('processed').attr('data-timestamp', Date.now());
大きなドキュメントやバッチ処理では、最適なメモリ使用量のためにcheerio.stringStream()などのstreaming APIの使用を検討してください。
ブラウザDOMやJSDOMの代わりにCheerioを使用すべきはいつですか?
サーバーサイドのHTMLパース、Webスクレイピング、静的HTML操作にはCheerioを使用してください。ブラウザのオーバーヘッドなしにjQueryライクな構文が必要な場合に最適です。クライアントサイドのインタラクションにはブラウザDOM、完全なブラウザシミュレーションにはJSDOM、動的コンテンツスクレイピングにはPuppeteerを選択してください。
// Perfect for server-side scraping
const $ = cheerio.load(htmlResponse);
const titles = $('h1, h2, h3').map((i, el) => $(el).text()).get();
// Great for email template processing
const emailHtml = cheerio.load(template);
emailHtml('.username').text(user.name);
emailHtml('.content').html(processedContent);
CheerioでさまざまなHTMLパーサーを扱うにはどうすればよいですか?
Cheerioはhtmlparser2(高速、寛容)とparse5(標準準拠)の両方をサポートしています。選択は用途によって決まります。形式が正しくないHTMLに対する速度と柔軟性が必要な場合はhtmlparser2を、厳密なHTML5準拠が必要な場合はparse5を使用してください。
// Using htmlparser2 (default, faster)
const $ = cheerio.load(html, {
xml: false,
decodeEntities: true
});
// Using parse5 (more compliant)
const $strict = cheerio.load(html, {
_useHtmlParser2: false,
xml: false
});
// For XML documents
const $xml = cheerio.load(xmlString, {
xmlMode: true,
decodeEntities: true
});
.attr()、.prop()、.data()の違いは何ですか?
.attr()は HTML属性を文字列として管理します.prop()は型変換と計算値を持つDOMプロパティを処理します.data()は自動JSON解析機能付きのHTML5データ属性を管理します
const $ = cheerio.load('<input type="checkbox" checked data-config=\'{"enabled": true}\'>');
// Attributes (string values)
$('input').attr('checked'); // 'checked'
$('input').attr('type'); // 'checkbox'
// Properties (computed/coerced values)
$('input').prop('checked'); // true (boolean)
$('input').prop('tagName'); // 'INPUT'
// Data attributes (with JSON parsing)
$('input').data('config'); // { enabled: true } (object)
CheerioでTypeScript型を適切に扱うにはどうすればよいですか?
型安全性を高めるために、型を明示的にimportし、ジェネリックパラメータを使用してください。このライブラリは適切な型推論を備えた包括的なTypeScriptサポートを提供しています。
import * as cheerio from 'cheerio';
import type { CheerioAPI, Cheerio, Element } from 'cheerio';
// Type the main API
const $: CheerioAPI = cheerio.load('<div>Content</div>');
// Type specific selections
const $elements: Cheerio<Element> = $('div');
// Use proper typing for element extraction
const elements: Element[] = $('div').get();
const firstElement: Element | undefined = $('div').get(0);
// Type function parameters correctly
$('div').each(function(this: Element, index: number) {
// 'this' is properly typed as Element
const $this = $(this);
});
なぜ「Cannot read property of undefined」エラーが発生するのですか?
これは通常、セレクターが要素にマッチしない場合に発生します。メソッドをチェーンしたり、プロパティにアクセスしたりする前に、常に要素が存在するかどうかを確認してください。
// ❌ Dangerous - may throw if no elements found
const title = $('.title').text().toUpperCase();
// ✅ Safe approach
const $title = $('.title');
const title = $title.length > 0 ? $title.text().toUpperCase() : '';
// ✅ Alternative with optional chaining
const title = $('.title').first().text() || '';
// ✅ Check before manipulating
if ($('.content').length > 0) {
$('.content').addClass('processed');
}
形式が正しくないHTMLやXMLドキュメントを処理するにはどうすればよいですか?
htmlparser2を使用する場合、Cheerioは形式が正しくないHTMLに対して寛容です。厳密なパースが必要な場合はparse5パーサーを使用するか、整形式のXMLドキュメントに対してXMLモードを有効にしてください。
// Forgiving HTML parsing (default)
const $ = cheerio.load('<div><p>Unclosed paragraph</div>');
// Strict XML parsing
const $xml = cheerio.load('<root><item/></root>', {
xmlMode: true,
withStartIndices: false,
withEndIndices: false
});
// Handle parsing errors gracefully
try {
const $ = cheerio.load(possiblyBadHTML);
return $('title').text();
} catch (error) {
console.error('HTML parsing failed:', error);
return '';
}
大きなHTMLドキュメントを効率的に処理するにはどうすればよいですか?
大きなドキュメントでは、すべてをメモリに一度に読み込むことを避けるためにstreaming APIを使用してください。これはWebスクレイピングや大きなファイルの処理において特に重要です。
import * as cheerio from 'cheerio';
import { createReadStream } from 'fs';
// Stream processing for large files
const stream = cheerio.stringStream({}, (err, $) => {
if (err) throw err;
// Process the document
const data = $('h1, h2, h3').map((i, el) => $(el).text()).get();
console.log(data);
});
createReadStream('large-file.html', { encoding: 'utf8' }).pipe(stream);
// For URLs with automatic encoding detection
const $ = await cheerio.fromURL('https://example.com', {
encoding: { defaultEncoding: 'utf8' }
});
Cheerioを使用する際のメモリへの影響はどの程度ですか?
Cheerioは完全なブラウザDOMよりも少ないメモリを使用する軽量なDOM表現を作成します。ただし、大きなドキュメントへの参照を保持したり、同時に多くのCheerioインスタンスを作成したりする場合は注意が必要です。
// ✅ Good - reuse the same instance
const $ = cheerio.load(html);
const results = [];
$('article').each((i, article) => {
const $article = $(article);
results.push({
title: $article.find('h1').text(),
content: $article.find('.content').text()
});
});
// ❌ Avoid - creates many instances
const articles = $('article').map((i, article) => {
return cheerio.load(article); // Don't do this
}).get();
参照を壊さずに要素をクローンするにはどうすればよいですか?
要素のディープコピーを作成するには.clone()メソッドを使用してください。要素を複数回再利用する必要がある場合や、元の要素の変更を避けたい場合に必須です。
const $ = cheerio.load('<div class="template">Template content</div>');
// Clone before modifying
const $template = $('.template');
const $copy1 = $template.clone().addClass('instance-1').text('Instance 1');
const $copy2 = $template.clone().addClass('instance-2').text('Instance 2');
// Original remains unchanged
console.log($template.text()); // 'Template content'
// Append clones to different parents
$('#container1').append($copy1);
$('#container2').append($copy2);
HTMLから構造化データを効率的に抽出するにはどうすればよいですか?
複雑なデータ抽出パターンには.extract()メソッドを使用してください。適切なTypeScriptサポートと共に、ドキュメントから複数の値を取得する宣言的な方法を提供します。
const $ = cheerio.load(productPageHtml);
// Extract structured data with type safety
const productData = $.root().extract({
title: 'h1.product-title',
price: '.price .amount',
images: [{ selector: '.gallery img', value: 'src' }],
features: ['.features li'],
specifications: {
selector: '.specs',
value: {
weight: '.weight',
dimensions: '.dimensions',
model: { selector: '.model', value: 'data-model' }
}
}
});
// Result is properly typed
console.log(productData.title); // string | undefined
console.log(productData.images); // string[]
console.log(productData.specifications?.model); // string | undefined
CSSセレクターのパフォーマンスに関するベストプラクティスは何ですか?
具体的なセレクターを使用し、過度に複雑なクエリを避けてください。IDセレクターが最も高速で、次にクラスセレクター、その次に属性セレクターです。可能な限り深い子孫セレクターは避けてください。
// ✅ Fast - specific selectors
const $navItems = $('#navigation .nav-item');
const $activeButton = $('.btn.active');
// ❌ Slower - overly complex selectors
const $badSelector = $('div > div > div span.small[data-type="special"]');
// ✅ Better - break down complex selections
const $container = $('.content-area');
const $items = $container.find('[data-type="special"]');
// ✅ Cache frequently used selections
const $document = $.root();
const $body = $document.find('body');
フォームデータとシリアライゼーションを適切に処理するにはどうすればよいですか?
構造化データには.serializeArray()を、URL-encodedな文字列には.serialize()を使用してください。これらのメソッドは自動的にフォーム検証ルールと要素タイプを処理します。
const $ = cheerio.load(formHtml);
// Get structured form data
const formData = $('form').serializeArray();
// [{ name: 'email', value: 'user@example.com' }, ...]
// Get URL-encoded string
const queryString = $('form').serialize();
// 'email=user@example.com&name=John'
// Handle specific form elements
const selectedOptions = $('select[multiple]').val(); // string[]
const checkboxValue = $('input[type="checkbox"]:checked').val(); // string | undefined
// Set form values programmatically
$('input[name="email"]').val('new@example.com');
$('select').val(['option1', 'option2']); // for multiple select
XSSを防ぐためにHTML属性を安全に変更するにはどうすればよいですか?
CheerioはXSS攻撃を防ぐために属性値を自動的にエンコードします。ただし、HTMLコンテンツの挿入には注意し、常にユーザー入力を検証してください。
const $ = cheerio.load('<div></div>');
// ✅ Safe - attributes are automatically encoded
const userInput = '<script>alert("XSS")</script>';
$('div').attr('title', userInput);
// Result: <div title="<script>alert("XSS")</script>"></div>
// ✅ Safe text insertion
$('div').text(userInput); // Automatically escaped
// ❌ Dangerous - raw HTML insertion
$('div').html(userInput); // Don't do this with user input
// ✅ Better - sanitize first or use text()
$('div').text(sanitizeInput(userInput));
Cheerioで非同期操作を処理する正しい方法は何ですか?
Cheerio自体は同期的ですが、URLの取得や複数のドキュメントの並行処理などのタスクに対してasync操作と組み合わせることができます。
// Load from URL (async)
const $ = await cheerio.fromURL('https://example.com');
const title = $('title').text();
// Process multiple URLs concurrently
const urls = ['https://site1.com', 'https://site2.com'];
const results = await Promise.all(
urls.map(async (url) => {
const $ = await cheerio.fromURL(url);
return {
url,
title: $('title').text(),
links: $('a[href]').map((i, el) => $(el).attr('href')).get()
};
})
);
// Combine with other async operations
async function processDocument(html: string) {
const $ = cheerio.load(html);
// Extract image URLs
const imageUrls = $('img[src]').map((i, el) => $(el).attr('src')).get();
// Process images asynchronously
const processedImages = await Promise.all(
imageUrls.map(url => processImage(url))
);
return { processedImages };
}