- 전체 파일 경로
- 크롤링 할 사이트 탐색하기
- build.gradle 의존성 추가
- News.class 파일 작성
- NewsService.class 파일 작성
- MainController.java 파일 수정
- news.html 파일 작성
- 크롤링 성공 화면
Jsoup이란?
- HTML을 가져오고 파싱할 수 있게 도와주는 자바 라이브러리이며, 자바에서 간단하게 크롤링 및 파싱이 가능
1. 전체 파일 경로
2. 크롤링 할 사이트 탐색하기
준비물1: 크롤링 할 사이트 주소
- https://www.hkbs.co.kr/news/articleList.html?sc_section_code=S1N1&view_type=sm
준비물2 : 크롤링 할 사이트 html 구조 및 가져올 데이터 확인
- section 의 ul li 안에 필요한 자료가 있는 것을 확인
- 이미지, 제목, 링크 데이터를 크롤링 할 것
3. bulid.gradle 의존성 추가
//jsoup 의존성 추가
implementation 'org.jsoup:jsoup:1.15.3'
4. News.class 파일 작성
크롤링한 데이터를 저장할 객체 만들기
- @Getter : 값을 가져오는 용도
- @ToString : 콘솔에서 값을 확인하는 용도
- @Builder : 값을 주입하여 객체를 만드는 용도
파일 경로 : com.mysite.sbb/news/News.class
@Getter
@Builder
@ToString
public class News {
private String image;
private String subject;
private String url;
}
5. NewsService.class 작성
-
파일 경로 : com.mysite.sbb/news/NewsService.class
@Service
public class NewsService {
private static String News_URL = "크롤링 할 URL";
@PostConstruct
public List<News> getNewsDatas() throws IOException {
List<News> newsList = new ArrayList<>();
Document document = Jsoup.connect(News_URL).get();
Elements contents = document.select("section ul.type2 li");
for (Element content : contents) {
News news = News.builder()
.image(content.select("a img").attr("abs:src")) // 이미지
.subject(content.select("h4 a").text()) // 제목
.url(content.select("a").attr("abs:href")) // 링크
.build();
newsList.add(news);
}
return newsList;
}
}
6. MainController.java 파일 수정
파일 경로 : com.mysite.sbb/MainController.java
@GetMapping("/news")
public String news(Model model) throws Exception{
List<News> newsList = newsService.getNewsDatas();
model.addAttribute("news", newsList);
return "news";
}
7. news.html 파일 작성
파일 경로 : resources/templates/news.html
<html layout:decorate="~{layout}">
<title>re:)Pick</title>
<div layout:fragment="content">
<div>
<table class= "table">
<tr>
<th>이미지</th>
<th>제목</th>
</tr>
<tr th:each="news : ${news} ">
<td><a th:href="${news.url}"><img th:src="${news.image}"></a></td>
<td><a th:href="${news.url}"><span th:text="${news.subject}"></span></a></td>
</a>
</tr>
</table>
</div>
</div>
</html>
8. 크롤링 성공 화면
참고 사이트
'Language > Springboot' 카테고리의 다른 글
[Springboot] 회원 정보(닉네임) 수정하기 (+추가 기능 구현 중) (0) | 2022.08.31 |
---|---|
[Stringboot] 네이버지도 API에 현재 위치 받아오기 (0) | 2022.08.28 |
[Stringboot] 제이쿼리(jQuery) 적용하기 (0) | 2022.08.28 |
[Springboot] 웹에 네이버지도 API 추가하기 (0) | 2022.08.26 |
[Stringboot] 게시글 댓글 페이징 기능 구현하기 (1) | 2022.08.25 |