ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 자바 스크래핑
    SpringBoot 2023. 5. 1. 11:16

    스크래핑 (Scraping) 이란? 

    시스템이나 웹사이트에 있는 정보(데이터) 중에서 필요한 정보를 추출 및 가공하여 제공하는 소프트웨어 기술입니다.

    이를 사용하면 여러 사이트에 있는 정보를 가져올 수 있습니다.

    다만, 타사이트에서 스크래핑을 통해 데이터를 가져오는 것은 민감한 부분이므로 보수적으로 진행해야 합니다.

     

    예제는 야후 파이넨설을 사용하였습니다. 사용하기 전에 야후 파이넨설의 루트 서버의 robots.txt 파일을 확인하겠습니다.

     

    제가 사용하려는 부분은 'finance.yahoo.com/quote/'을 사용하기 때문에 disallow가 되지 않았습니다.

    Intellilj gradle에서 'implementation 'org.jsoup:jsoup:1.7.2' 의존성을 추가해주고 아래와 같은 코드를 작성합니다.

    public static void main(String[] args) {
    
            Connection connection = Jsoup.connect(url);
            try {
                Document document = connection.get();
    
                Elements attributeValue = document.getElementsByAttributeValue("data-test", "historical-prices"); //스크래핑 해올 부분
                Element ele = attributeValue.get(0);
    
                Element tbody = ele.children().get(1);
                for(Element e :tbody.children()){
                    String txt = e.text();
                    if(!txt.endsWith("Dividend")){
                        continue;
                    }
                    String[] splits = txt.split(" ");
                    String month = splits[0];
                    int day = Integer.valueOf(splits[1].replace(",",""));
                    int year = Integer.valueOf(splits[2]);
                    String dividend = splits[3];
    
                    System.out.println(year + "/" + month + "/" + day + "->" + dividend);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    html에서 스크래핑 해올 부분을 개발자 도구를 통해 찾은 후 parse하여 원하는 형식으로 가져옵니다.

    아래는 스크래핑 결과입니다.

     

Designed by Tistory.