이번에는 자바 스프링으로 크롤링을 해볼 생각이다.
빠른속도로 실행할 수 있는 Jsoup 라이브러리를 사용하였다.( 직관적이고 경량화가 되어 있어서 가장 보편적으로 사용한다고 카드라..)
먼저 컨트롤러의 전체 코드를 보자면 다음과 같다.
package com.example.demo.Controller;
import com.example.demo.Service.CrawlingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CrawlingController {
@Autowired
private CrawlingService crawlingService;
@GetMapping("/crawl")
public String crawl(@RequestParam String url) {
return crawlingService.fetchPostTitlesAndLinks(url);
}
}
Get Mapping을 사용하여 /crawl경로에서 url을 입력하면 서비스로 전달하는 매우 간단한 코드이다.
package com.example.demo.Service;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class CrawlingService {
// 글 목록의 제목과 링크를 가져오는 메서드
public String fetchPostTitlesAndLinks(String url) {
try {
// Jsoup을 사용하여 갤러리 메인 페이지를 추출
Document document = Jsoup.connect(url).get();
// 게시글 제목과 링크 요소를 선택
Elements titleElements = document.select(".ub-content .gall_tit a");
// 각 제목과 링크를 저장할 리스트
List<String> posts = new ArrayList<>();
for (Element titleElement : titleElements) {
// 제목 텍스트
String title = titleElement.text();
// 링크 URL
String link = titleElement.absUrl("href");
// 제목과 링크를 합치기
posts.add("Title: " + title + "\nLink: " + link);
}
// 가져온 제목과 링크를 줄바꿈으로 연결하여 반환
return String.join("\n\n", posts);
} catch (Exception e) {
e.printStackTrace();
return "Failed to fetch titles and links";
}
}
}
이제 실질적인 기능을 담아둔 서비스 코드를 살펴보자.
우선, Jsoup.connect함수를 통해 url링크를 담아두고 url에 해당되는 메인 페이지를 추출시키자.
추출 시킨 데이터를 담은 document 에서 이제 특정 요소들을 추출 시켜야하는데, .select를 사용해 셀렉터로 지정해야한다.
필자가 추출하려는 사이트의 경우, ub-content와 gall_tit a라는 클래스를 사용하고 있어, 해당 클래스로 추출해줬다.
후에, 선택한 요소를 for문을 통해 posts라는 List 배열에 집어 넣어 제목은 .text()를 통해 추출시키고
.absUrl을 사용하여 href요소를 가져왔다.
'자바 스프링' 카테고리의 다른 글
| java.lang.IllegalArgumentException: The Unicode character at code point [49,548] cannot be encoded as it is outside the permitted range of 0 to 255 (0) | 2025.02.08 |
|---|---|
| 타임리프 @RequestParm 값 넘겨주기 문제 (0) | 2025.02.08 |
| IOC 컨테이너(스프링 컨테이너)와 제어의 역전에 대하여 (0) | 2024.05.11 |
| React Session 저장문제 (0) | 2024.01.10 |
| 자바 스프링 의존성 주입 (1) | 2024.01.08 |