Skip to content

Cheerio โ€‹

Node.js ็Žฏๅขƒไธ‹็š„ HTML/XML ่งฃๆžๅบ“๏ผŒๆไพ› jQuery ้ฃŽๆ ผ็š„้€‰ๆ‹ฉๅ™จ APIใ€‚

https://cheerio.js.org/

feature โ€‹

  • ้€Ÿๅบฆๆžๅฟซ
  • ้€‚ๅˆ็ˆฌ่™ซใ€้™ๆ€้กต้ข่งฃๆž
  • ้€‚ๅˆ็ป“ๆž„ๅŒ–ๆๅ–

WARNING

ๅฎƒไธๆ‰ง่กŒ JSใ€ไธๆธฒๆŸ“้กต้ข๏ผŒๅ› ๆญค๏ผš

install โ€‹

bash
npm install cheerio

usage โ€‹

js
import * as cheerio from 'cheerio';
js
const cheerio = require('cheerio');

API โ€‹

js
$('h1')
$('.item')
$('#main')
$('ul li:first-child')
js
$('h1').text()
js
$('img').attr('src')
js
$('li').each((i, el) => {
  console.log($(el).text());
});
js
$('title').text('New Title');
$('body').append('<p>Hello</p>');
js
$.html()

example โ€‹

js
import * as cheerio from 'cheerio';

const html = `
<ul id="fruits">
  <li class="apple">Apple</li>
  <li class="orange">Orange</li>
  <li class="pear">Pear</li>
</ul>
`;

const $ = cheerio.load(html);

console.log($('.apple').text()); // Apple
console.log($('#fruits li').length); // 3

Released under the MIT License.