1. 프로그래밍/1-2. Java
Java - [ Jsoup 이용한 크롤링 ]
yunyj99
2022. 5. 2. 11:04
Jsoup이란 자바로 만들어진 HTML parser로, DOM 구조를 추적하거나 CSS 선택자를 사용하여 데이터를 찾아 추출할 수 있다.
우선 라이브러리 설치를 위해 https://jsoup.org/download 이동
제일 위 jsoup-1.14.3.jar 파일 다운로드
그리고 사용할 프로젝트에 라이브러리를 설치해주면 된다.
JSOUP을 이용해 영화 정보를 가져와 JSON 형태로 데이터를 생성해주었다.
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
public class crawling {
public static void main(String[] args) {
// Jsoup를 이용해서 크롤링
String url = "http://www.cgv.co.kr/movies/"; // 크롤링할 url지정
Document doc = null; // Document에 페이지의 전체 소스가 저장됨
try {
doc = Jsoup.connect(url).get();
} catch (IOException e) {
e.printStackTrace();
}
// select를 이용하여 원하는 태그를 선택
Elements ranks = doc.select(".rank");
Elements imgs = doc.select(".thumb-image > img");
Elements movieAges = doc.select(".ico-grade");
Elements movieTitles = doc.select("div.box-contents strong.title");
Elements movieRates = doc.select(".percent > span");
Elements movieOpenDates = doc.select(".txt-info > strong");
// JSON 형태로 영화 정보 저장
JSONArray movieList = new JSONArray();
for (int i = 0; i < ranks.size(); i++) {
// JSONObject에 키:값 형태로 데이터 저장
JSONObject obj = new JSONObject();
obj.put("rank", ranks.get(i).text());
obj.put("img", imgs.get(i).attr("src"));
obj.put("movieAge", movieAges.get(i).text());
obj.put("movieTitle", movieTitles.get(i).text());
obj.put("movieRate", movieRates.get(i).text());
obj.put("movieOpenDate", movieOpenDates.get(i).text());
// movieList에 생성한 JSONObject 추가
movieList.add(obj);
}
// System.out.println(" movieList : " + movieList);
}
}
클래스명 | 설명 |
Document | Jsoup 얻어온 결과 HTML 전체 문서 |
Element | Document의 HTML 요소 |
Elements | Element가 모인 자료형. for나 while 등 반복문 사용이 가능 |
Connection | Jsoup의 connect 혹은 설정 메소드들을 이용해 만들어지는 객체, 연결을 하기 위한 정보를 담고 있음 |
Response | Jsoup가 URL에 접속해 얻어온 결과. Document와 다르게 status 코드, status 메시지나 charset같은 헤더 메시지와 쿠키등을 가지고 있음 |
참조
더보기
https://ming9mon.tistory.com/41
자바 Jsoup를 이용한 웹 크롤링 예제
크롤링 라이브러리 Jsoup 크롤링을 위한 라이브러리는 많지만 그 중 Jsoup를 이용한 크롤링을 소개하고자 한다. Jsoup이란 자바로 만들어진 HTML parser다. Jsoup는 DOM 구조를 추적하거나 CSS 선택자를 사
ming9mon.tistory.com
https://loy124.tistory.com/193
크롤링을 활용한 Spring 영화 예매 사이트 구현하기(CGV CLONE)
GITHUB 주소(주요 commit은 다른 프로젝트에서 하다 옮겨서 commit 누적이 없다..) https://github.com/loy124/CGV_Clone loy124/CGV_Clone Spring + mybatis + html + javascript + css CGV 사이트 크롤링을 활용..
loy124.tistory.com