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());
})
'Node.js' 카테고리의 다른 글
puppeteer (0) | 2024.08.17 |
---|---|
selenium v4.0 (javascript) (0) | 2024.08.09 |
크레이지 아케이드 멀티게임(모작) (0) | 2023.08.26 |
웹소켓(WebSocket) 8장 - socket.io와 lockstep (0) | 2023.08.24 |
웹소켓(WebSocket) 7장 - socket.io를 이용한 게임 동기화(마우스 위치 전송) (0) | 2023.08.01 |