본문 바로가기
유지보수/메인페이지 개편

[메인페이지 개편-3] Spring - 네이버 블로그 크롤링(jsoup) list 담아서 불러오기

by 죠졍니 2024. 1. 24.
728x90
반응형
SMALL

 

 

<조건>
1. spring(전자정부프레임워크3.9)
2. jsp에서만 사용가능
3. 블로그 썸네일, 이름, 날짜 호출

 

 

 

 

네이버 블로그 크롤링  작업은 spring환경에서 하는게 많이 안나와있다.  보통 파이썬으로 크롤링해서 그런가...

하지만 내가 이번에 만들어야 하는건 다음 조건을 만족하며 크롤링 해와야 한다.

 

다양한 방법이 있지만 나는 jsoup을 사용하여 jsp에 크롤링 및 호출을 전부 담아낼 것이다.

 

 

 

소스코드 - jstl (자바와 같음)

 

 

<%@ page import ="org.jsoup.Jsoup" %>
<%@ page import ="org.jsoup.nodes.Element" %>
<%@ page import ="org.jsoup.nodes.Document" %>
<%@ page import ="org.jsoup.select.Elements" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>


<%
		// 네이버 블로그 url로 document가져오기
		Document doc = Jsoup.connect("블로그 주소").get();
	
    
    //여기서부터는 각자 원하는 태그 확인하여 가져와야함
		// iframe 태그에 있는 진짜 블로그 주소 가져오기
		Elements iframes = doc.select("iframe#mainFrame");
		String src = iframes.attr("src");
		//진짜 블로그 주소 document 가져오기
		Document doc2 = Jsoup.connect(src).get();
		//System.err.println("주소 확인용 : " +src);
		//System.out.println("doc2 : "+doc2);
		// 블로그에서 원하는 블로그 페이지 가져오기
		String[] blog_logNo = src.split("&");
		String[] logNo_split = blog_logNo[1].split("=");
		String logNo = logNo_split[1];
		
		// 찾고자 하는 블로그 본문 가져오기
		String real_blog_addr = "div#post-view" + logNo;
		
		Elements blog_element = doc2.select(real_blog_addr);
		// 블로그 썸네일 가져오기
		
		String image = "div.post > div.post-back > table.post-body > tbody > tr > td.bcc > div#prologue > dl.p_post_top";
		
		Elements image_element = doc2.select(image);
		String og_image = "dd.p_photo_d > p.p_img > a > img";
		String og_other = "dd.p_photo_d > ul";
		//String og_image = doc2.select("div.post > div.post-back > table.post-body > tbody > tr > td.bcc > div#prologue > dl.p_post_top > dd.p_photo_d > p.p_img > a > img").get(0).attr("src");
		
        
        <!--리스트로 담기-->
		List<String> imageList = new ArrayList<>();
		List<String> otherList = new ArrayList<>();
		
		for (int i = 0; i < 5; i++) {
			imageList.add(doc2.select(og_image).get(i).attr("src"));
			otherList.add(doc2.select(og_other).get(i).html());
		}
		

		System.err.println("imageList : " + imageList);
		System.err.println("otherList : " + otherList);
		
%>

 

 

 

블로그 중에서도 각자 원하는 내용과 각 코드가 다 다르기 때문에 내가 원하는 태그만 추출해 내는것이 중요하다.

중간중간에

 

System.out.println 을 활용하여 잘 가져와지는지 눈으로 확인하면 더 편리하다.

 

 

 

 

소스코드 - html

리스트에 담은 블로그 내용을 이제  뿌려줄 차례이다.

<c:set var="otherList" value="<%=otherList%>"/>
<c:set var="imageList" value="<%=imageList%>"/>


<!--html 내용 일부 -->
<table>
	 	<c:forEach var="imageList" items="${imageList}">
	 	   <img referrerpolicy="no-referrer" target="_blank" src=<c:out value="${imageList}"/>>
		</c:forEach>
		<c:forEach var="otherList" items="${otherList}" >
		   <c:out value="${otherList}" escapeXml="false"/>
		</c:forEach>
</table>

 

다음과 같이 태그를 활용하여 리스트 전체를 뿌려준다.

 

 

 

 

 

느낀점 : 개인적으로 이미지 불러오는게 힘들었다. 이미지 자체가 저작권 문제로도 많이 잡히기도 하고 여러문제가 자꾸 발생해서 시간이 상당히 소요됐다. 하지만 결과적으로는 성공~!

728x90
반응형
LIST