본문 바로가기

개발기술/Web Dev

웹 스크래핑 Jsoup

스크래핑 활용분야

  여러 쇼핑몰의 데이터를 스크래핑해서 쇼핑몰간의 가격비교사이트, 특정 카테고리에 해당하는 아이템 모아서 한번에 보여주는 사이트, 여러회사의 취업공고를 모아서 보여주는 사이트, 업무 자동화, 핀테크 회사에서 사용자대신 공공데이터를 스크래핑 후 서류제출과정 대신하여 간편화, 무궁무진한 활용가능함

 

스크래핑 정책

  main페이지의 robot.txt(https://finance.yahoo.com/robots.txt)을 조회하면 해당 사이트의 스크래핑 정책을 확인할 수 있다. 스크래핑을 허용한다고하여도 해당 사이트에 부하가 걸리지 않는 정도에서 운영하여야한다. 

 

스크래핑 

  •  Jsoup library는 beautiful Soup의 java버전으로 해당 라이브러리를 사용한다.
  • 개발자는 자신의 서비스가 의존하고 있는 외부서비스에 대해서 충분히 이해해야하는데, URL parameter을 통해서 내부로직 조회없이 많은 정보를 얻어 낼 수 있음.

Jsoup

  • Jsoup.connect(URL) : Connection 객체를 생성함
  • Connectioninstance.get() : Connection 객체를 통해서 Document 객체를 생성함
  • Documentinstance.getElementsBySomething() : 조건에 해당하는 복수의 element들을 collectiond으로 받는 elements 객체를 생성함

 

Elements

  java.util.ArrayList<element>를 상속받은 객체

  • elementsinstance.get(i) : i index에 있는 element를 return함
  • elementinstance.children() : html 구조상 child인 elements를 반환함. If this element has no children, returns an empty list.
  • elementinstance.text() : html의 tag들을 모두 지우고 contents인 text만 반환함.

try {
    Connection connect = Jsoup.connect("https://finance.yahoo.com/" +
            "quote/COKE/history/?frequency=1mo&period1=99153000&period2=1722993803");
    Document document = connect.get();
    Elements elements = document.
            getElementsByClass("table yf-ewueuo");
    // 유일한 matching element 산출
    Element elementcontents = elements.get(0);

    // table의 children -> children 중 tbody -> tbody의 요소들 선택
    Elements tbodies = elementcontents.children().get(1).children();
    
    for (Element tbody : tbodies) {
        if(tbody.text().endsWith("Dividend")){
            String[] splitTbody = tbody.text().split(" ");
            String month = splitTbody[0];
            String day = splitTbody[1].replace(",", "");
            String year = splitTbody[2];
            String diviend = splitTbody[3];
            System.out.println(year + "/" + month + "/" + day + "->" + diviend);
        }
    }

} catch (IOException e) {
    throw new RuntimeException(e);
}

https://jsoup.org/