[nest.js] curl 을 이용한 crawling

nest.js로( 정확히는 node.js )로 web scraping 을 하는 방법은 몇가지가 있는데 그중 가장 간단해 보이는 내용을 기록한다.

준비물
  • nest.js
  • axios
  • 대상 url과 parameters

axios 설치

nest.js는 기본으로 준비되었을 것이고 axios 를 설치하자.

npm -i --save axios cheerio

cheerio 는 html 내용을 parsing 할 때 필요하므로 한번에 받는다.

curl 알아내기

크롬, 엣지, 파이어폭스 등에서 개발자도구를 통해 가져올 url을 curl로 변환시킨다.

curl -> node.js axios code 변환
Convert curl commands to code
Utility for converting cURL commands to code

위 사이트에 가서 복사한 curl을 붙여넣기 한 뒤 node.js 탭을 눌러주면 자동으로 변환시켜준다.
( 엣지에서는 런타임에러가 발생해서 파이어폭스에서 하니 잘 되었다 )

code test

간단한 api를 만들어서 호출하면 html 내용이 출력된다.

curl로 가져온 html 한글이 깨질 때( euc-kr 인코딩된 페이지 한글깨짐 )

axios 호출 config 변수에 responseType : "arraybuffer" 를 추가한 뒤

const html : string = iconv.decode( response.data, "EUC-KR" ).toString();

위 코드처럼 decode하면 된다.

Subscribe to X세대 신입사원

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe
774-86-01972 cinnabar.3d@gmail.com