-
[Spring] Spring에서 Selenium(셀레니움) 사용해 크롤링하기Backend/Spring 2023. 6. 14. 01:03
시작
Spring 프로젝트에서 크롤링을 하기위해 라이브러리를 찾던 중 JSoup과 Selenium을 발견했다. 나의 크롤링의 경우 단순히 긁어오는 것이 아니라 페이지 이동, 동작이 필요했는데 JSoup은 동적 웹페이지가 안되는 것 같았다. 그래서 Selenium으로 결정했다. 크롬을 가장 많이 사용하는 것 같아 크롬브라우저를 사용할 것이다.
크롬 브라우저 버전 확인
크롬 브라우저에 접속하여 메뉴 → 설정 → Chrome정보 에서 크롬 버전을 확인할 수 있다.
크롬 드라이버 설치
다음 링크에서 크롬 브라우저 버전에 맞는 드라이버를 설치한다.
ChromeDriver - WebDriver for Chrome - Downloads
Current Releases If you are using Chrome version 115 or newer, please consult the Chrome for Testing availability dashboard. This page provides convenient JSON endpoints for specific ChromeDriver version downloading. For older version of Chrome, please see
chromedriver.chromium.org
설치 후 압축을 풀고 원하는 경로에 위치시킨 뒤 해당 경로를 Spring에서 사용한다.
Spring 의존성 설정
selenium 라이브러리를 사용하기 위해 다음 코드를 build.gradle에 추가해주었다.
// 기존 의존성 implementation 'org.seleniumhq.selenium:selenium-java:4.10.0' // CDP 의존성 implementation files('libs/selenium-devtools-v86-4.1.2.jar')
Driver 설정
웹드라이버 ID와 웹 드라이버 경로를 설정하고 Chrome Option을 정의하여 ChromeDriver 생성한다.
로컬에서 작업한다면 크롬드라이버가 있는 경로를 확인하고 절대경로로 적어주면 된다.
@Service public class CrawlerService { //WebDriver private WebDriver driver; //Chrome Options; private ChromeOptions options; //Properties private final String WEB_DRIVER_ID = "webdriver.chrome.driver"; private String WEB_DRIVER_PATH = "chromedriver"; //크롤링 할 URL private String base_url; public CrawlerService() { //System Property SetUp System.setProperty(WEB_DRIVER_ID, WEB_DRIVER_PATH); options = new ChromeOptions(); options.addArguments("--disable-popup-blocking"); options.addArguments("--disable-default-apps"); options.addArguments("--disable-notifications"); options.addArguments("--disable-blink-features=AutomationControlled"); base_url = "https://naver.com"; driver = new ChromeDriver(options); }
크롤링하기
public void crawler(String id, String password) { //Driver SetUp try { // 이러닝 사이트 접근 driver.get(base_url); Thread.sleep(3000); WebElement element = driver.findElement(By.cssSelector("selector path")); Thread.sleep(3000); element.click(); element.sendKeys("key"); List<WebElement> element = driver.findElements(By.className("classname")); } catch (Exception e) { System.out.println(e.getMessage()); } driver.close(); } }
- findElement
- element 하나를 찾아 반환한다.
- 조건으로는 By를 통해 여러가지 방법을 찾을 수 있다.
- By.cssSelector
- By.className
- By.tagname
- By.id
- By.xpath
- 등등
- findElements
- 조건에 해당하는 element 여러개를 반환한다.
- List형으로 받을 수 있다.
- click()
- 클릭시 이벤트가 적용된 대상에 대해 클릭을 한다.
- sendKeys()
- input에 대해 인자값으로 입력 값을 넣는다.
- Thread.sleep()
- 렌더링 이후 동적으로 값들이 표시된 후에 요소들의 선택하거나 동작시켜 정확하게 동작하도록
- sleep을 통해 시간 지연을 넣는다.
끝
크롤링 시에 페이지 렌더링을 고려하며 크롤링하기란 쉽지 않은 것 같다. 아직은 sleep을 통해 해결하다보니 시간 지연이 많아 응답을 받기까지 시간이 오래걸린다. 어떻게 하면 빠르게 할 수 있지..?
'Backend > Spring' 카테고리의 다른 글
- findElement