티스토리 뷰
Maven MVC Porject 에서 Jsoup을 활용한 크롤링을 공부하면서 절차를 정리해보려 한다
1편은 연동 및 간단한 확인 예제를 통해 크롤링이 되는지 보는것이 목적이다.
jsoup 설정 및 사용법
jsoup 이란..
- 파이썬 HTML 파서가> BeautifulSoup
- 자바 HTML 파서가 > jsoup
- jsoup은 HTML 문서를 읽어들인 후에 DOM 객체로 변환을 하게 된다.
- jsoup의 selector api를 이용해서 특정 Element에 접근을 할 수 있다.
- 해당 Element의 정보를 읽거나 수정할 수 있습니다.
- jsoup은 jquery의 selector와 비슷한 selector api를 제공하기 때문에 쉽게 사용할 수 있습니다.
- jsoup의 selector api를 이용해서 특정 Element에 접근을 할 수 있다.
- 해당 Element의 정보를 읽거나 수정할 수 있습니다.
- jsoup은 jquery의 selector와 비슷한 selector api를 제공하기 때문에 쉽게 사용할 수 있습니다.
1. 설치
- Clink!! jsoup 설치 Link...
- jsoup-1.11.2.jar core library
- jsoup-1.11.2-sources.jar optional sources jar
- jsoup-1.11.2-javadoc.jar optional javadoc jar
- 기본적으로 jsoup-1.11.2.jar 설치하여 적용, jsoup-1.11.2-sources.jar, jsoup-1.11.2-javadoc.jar은 jsoup의 설정의 소스를 보려면 다운
2. Maven dependency 추가
<dependency> <!-- jsoup HTML parser library @ https://jsoup.org/ --> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.11.2</version></dependency>
3. Gradle 추가
// jsoup HTML parser library @ https://jsoup.org/compile 'org.jsoup:jsoup:1.11.3'
4. GET 기본 소스
try { // 1. URL 선언 String connUrl = "naver.com"; // 2. HTML 가져오기 Document doc = Jsoup.connect(connUrl).get(); // 3. 가져온 HTML Document 를 확인하기 System.out.println(doc.toString());} catch (IOException e) { // Exp : Connection Fail e.printStackTrace();}
5. POST 기본 소스
try { // 1. URL 선언 String connUrl = "https://naver.com"; // 2. HTML 가져오기 Document doc = Jsoup.connect(connUrl).post(); // TODO POST의 data 값은 Jsoup.data(...) 을 사용하시면 됩니다. // 3. 가져온 HTML Document 를 확인하기 System.out.println(doc.toString());} catch (IOException e) { // Exp : Connection Fail e.printStackTrace();}
6. Maven Project Test 예제 소스
- Controller.java...
@Controllerpublic class HomeController {private static final Logger logger = LoggerFactory.getLogger(HomeController.class);@RequestMapping(value = "/", method = RequestMethod.GET)public ModelAndView home() throws IOException {ModelAndView model = new ModelAndView();model.setViewName("/home");model.addObject("testString", "input search keyword..");model.addObject("naver1", getCurrencyTest("naver")[0]);model.addObject("naver2", getCurrencyTest("naver")[1]);model.addObject("google1", getCurrencyTest("google")[0]);model.addObject("google2", getCurrencyTest("google")[1]);return model;}
// 여기서는 getCurrencyRate를 호출한 Caller에서 예외처리를 하도록 throws로 선언합니다. public static String[] getCurrencyTest(String type) throws IOException { String returnMessage1 = "do not return message1..." + type; String returnMessage2 = "do not return message2..." + type; if (type.equals("naver")) { try { String connUrl = "https://www.naver.com"; Document doc2 = Jsoup.connect(connUrl).post(); returnMessage1 = doc2.toString(); returnMessage2 = doc2.data(); } catch (IOException e) { e.printStackTrace(); } }else { try { String connUrl = "https://www.google.com"; Document doc2 = Jsoup.connect(connUrl).post(); returnMessage1 = doc2.toString(); returnMessage2 = doc2.data(); } catch (IOException e) { e.printStackTrace(); } } String returnMessage[] = {returnMessage1, returnMessage2}; return returnMessage; }}
- view.jsp...
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ page session="false" %>
<div class="google_area" name="google1" style="margin: 20%"> ${google1 } </div>
<div class="google_area" name="google2" style="margin: 20%"> ${google2 } </div>
<div class="naver_area" name="naver1" style="margin: 20%"> ${naver1 } </div>
<div class="naver_area" name="naver2" style="margin: 20%"> ${naver2 } </div>
<script type="text/javascript"> </script>
아래는 Tomcat을 통한 크롬에서 소스 실행결과 캡처 화면이다.
> 구글은 ssl 문제인지 아래와 같은 에러로그가 나오고 캡처와 같이 불러오지를 못하였다
2. 네이버
> 네이버의 경우 인코딩 부분이 없어 "???????" 와 같이 문자를 읽어 오지 못하는 것으로 보인다..
- 실행결과...
- naver 는 제대로 긁어오는데 google의 경우는 ssl(https) 이슈가 있는 것으로 보임..
org.jsoup.HttpStatusException: HTTP error fetching URL. Status=405, URL=https://www.google.com at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:760) at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:706) at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:299) at org.jsoup.helper.HttpConnection.post(HttpConnection.java:294) at com.bykwon.spring.HomeController.getCurrencyTest(HomeController.java:63) at com.bykwon.spring.HomeController.home(HomeController.java:40)
<<< Google 소스 상 크롤링 한 캡처 화면 >>>
<<< Naver 소스 상 크롤링 한 캡처 화면 >>>
다음편에서는 구글 / 네이버 각각의 이슈에 대해 원인 및 조치를 해볼까한다...
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 서버
- 통합
- 환경변수
- mysql
- 백준 알고리즘
- 구축
- Eclipse
- Maven
- 알고리즘
- Algorithm
- 자바
- 순열
- 리눅스
- 통합개발환경
- LeetCode
- IDE
- Oracle
- jdk
- Tomcat
- 문제풀이
- CentOS7
- centos
- spring
- Java
- 설정
- 백준
- 개발환경
- 개발
- 연동
- sts
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
글 보관함