IT 기술/[React] Project
7. 내 블로그 크롤링 (Crawling)
Lee Hye Won
2021. 6. 1. 14:36
axios 와 cheerio 를 사용해서 내 블로그를 Crawling 했다.
Axios
JavaScript 를 이용해 AJAX Request 를 할 수 있는 라이브러리이다.
(AJAX : Asynchronous JavaScript and XML, 비동기적으로 JSON 이나 XML 등의 데이터를 받을 수 있는 방법)
cheerio
jQuery 처럼 DOM Selector 기능을 제공한다. axios 로 받은 HTML 데이터에서 내가 크롤링할 정보만을 추출하는 곳에 사용할 것이다.
exports.crawlBlog = async (ctx) => {
let htmlData = [];
// axios 를 활용해서 AJAX로 HTML 문서를 가져온다.
const getHTML = () => {
try {
return axios.get('가져올 문서의 URL');
} catch (e) {
console.error(e);
}
};
let result = [];
let resultList = [];
let data = [];
// getHTML 함수 실행 후 데이터에서 div.se-section-documentTitle 인 리스트를 postList에 저장
await getHTML()
.then((html) => {
const $ = cheerio.load(html.data);
const $postList = $('div.se-section-documentTitle');
$postList.each(function (i, el) {
result[i] = {
date: $(this).find('span.se_publishDate').text(),
category: $(this).children('div.blog2_series').find('a').text(),
title: $(this).children('div.pcol1').find('span').text(),
author: $(this).children('div.blog2_container').find('a').text(),
hits: 0
};
});
return result;
})
.then((res) => {
console.log(result);
});
ctx.body = result;
};