[sanitize-html] iconv없이 한글 웹페이지 크롤링하기

Jinseok Lee·2018년 12월 4일
5
post-thumbnail

사연

request모듈을 활용해서 한글 웹페이지를 받아 온 다음 cheerio를 써서 엘리먼트를 찾아 그 안에서 html을 가져오는 작업이었는데, html이 깨져서 출력되었다.

request(requestOptions, function (err, res, body) {
  const $ = cheerio.load(body, {decodeEntities: true});
  const content = $('.article__content'); 
  
  console.log(content.html());
});
지급해드릴 예정이오니

삽질

해결하기 위해 검색해보니 iconv를 사용하면 된다고 해서 사용해보려고 하니 설치할 때 문제도 생기고 파이썬 버전 문제 등등 영 마음에 들지 않았다. iconv-lite를 사용해보아도 크롤링한 전체 텍스트는 한글로 변환되어서 잘 나오는데 cheerio를 통해 load 이후 html()로 호출해보면 역시나 깨져 나오는 것이었다 ㅠㅠ

해결

그렇게 깃헙이슈를 돌아다니다가 한가지 해결책을 찾았는데 그 것이 바로 sanitize-html이라는 npm 라이브러리였다. star도 1,000개 이상이어서 신뢰가 갔다. sanitize-htmlparser 옵션 중 decodeEntitiestrue로 하니까 제대로 한글이 나타나게 되었다!

const sanitizeHtml = require('sanitize-html');
...
request(requestOptions, function (err, res, body) {
  const $ = cheerio.load(body, {decodeEntities: true});
  const content = sanitizeHtml($('.article__content'), {
    parser: {
      decodeEntities: true
    }
  });
  
  console.log(content);
});
profile
전 위메프, 이직준비중

2개의 댓글

comment-user-thumbnail
2018년 12월 5일

삽질하는 배너가 귀여워요~!

1개의 답글