[javascript] 크롤링

SuJin·2023년 2월 2일
0

JavaScript

목록 보기
7/7

javascript로 크롤링을 하면서
안에 있는 내용까지 크롤링을 해주는 방법을 없을까?
라는 생각을 하게 되었고 <a> 태그 제목에 href 링크를 가지고 오려면 어떻게 해야할까.. 라는 생각을 하게 되었다.

axioscheerio를 사용하여 크롤링을 진행했고,

  const resp = await axios.get("크롤링 주소");

  const $ = cheerio.load(resp.data); 
  const elements = $(".widget-contents a"); 
  console.log(typeof elements);
  elements.each((idx, el) => {
    console.log($(el).text());
  });

이렇게만 사용하면 콘솔창에는 제목만 뜬다.

여기서 elements만 콘솔 창에 출력을 해보면 object 형식으로 출력이 되는데

이렇게 href: '~~~~~~~' 내용이 들어가 있는것을 볼 수 있다.


그래서 href 내용을 담은 배열을 따로 선언해주었고

  const hrefarr =[];

  $(".widget-contents")
    .find("li")
    .each(function (index, ele) {
      var dt1 = $(this).find("h4").eq(0);
      // console.log("href", dt1.find("a").attr("href"));
      if(dt1.find("a").attr("href") !== undefined){
        hrefarr.push(dt1.find("a").attr("href"))
      }
      console.log('arr', hrefarr)
      console.log("***");
    });

만든 hrefarr의 내용은
위와 같았다.

그래서 기존 url에다가 첫글자가 ? 일때와 아닐때를 구분하여

  for (let i = 0 ; i < hrefarr.length; i++){
    if(hrefarr[i][0] === '?'){
      const hrefresp = await axios.get("링크" + hrefarr[i]);
      hrefContents(hrefresp);
    }
    else{
      const slice = hrefarr[i].slice(10)
      const hrefresp = await axios.get("링크" + slice)
      hrefContents(hrefresp);
    }
  }

위에서 사용했던 크롤링 함수를 그대로 사용하여 그 안에다가 data를 넣어주었다.

async function hrefContents(resp) {
  const $ = cheerio.load(resp.data); // ❷ HTML을 파싱하고 DOM 생성하기
  const elements = $(".summary-info pre"); // ❸ CSS 셀렉터로 원하는 요소 찾기
  // ➍ 찾은 요소를 순회하면서 요소가 가진 텍스트를 출력하기
  elements.each((idx, el) => {
    // ❺ text() 메서드를 사용하기 위해 Node 객체인 el을 $로 감싸서 cheerio 객체로 변환
    console.log($(el).text());
  });
}

위 내용들을 코드로 출력하면

내가 선정한 title과 그에 맞는 내용이 일치한다!!!



[참고] : https://www.letmecompile.com/javascript-crawler-tutorial-intro/
[참고] : https://118k.tistory.com/241

profile
Anyone can be anything.

0개의 댓글