Node.js

cheerio module

blackbearwow 2024. 8. 8. 02:19

cheerio document: https://cheerio.js.org/

cheerio는 HTML과 XML을 파싱하고 다루는 라이브러리이다.

 

cheerio 설치:

npm install cheerio --no-audit

cheerio import:

const cheerio = require('cheerio');

 

document 로딩:

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

load메소드로 문자열을 로드해 Cheerio 객체를 반환한다. 이 객체를 이용해 DOM을 횡단하거나 데이터를 다룰 수 있다.

 

elements 선택:

$('h2.title').text(); // "Hello world"

css selector를 이용해 document에서 element를 선택할 수 있다.

 

DOM 횡단하기:

Cheerio 객체는 DOM 요소의 배열과 비슷하다. 

$('h2.title').find('.subtitle').text();

 

elements 조작하기:

$('h2.title').text('Hello there!');
$('h2').after('<h3>How are you?</h3>');

h2태그의 titile클래스인 요소의 텍스트를 바꾼다.

h2태그 뒤에 h3태그의 요소를 추가한다.

 

메소드들: https://cheerio.js.org/classes/Cheerio.html

 

예시

const cheerio = require('cheerio');
//중략
.then(function(response){
    const data = response.data;
    let $ = cheerio.load(data);
    let titles = $('.class');
    console.log(titles.text());
})