KoreaIt Academy/JAVA

[JAVA] 크롤링(Crawling)

hongeeii 2021. 8. 24.
728x90
반응형

웹 크롤링(실시간 데이터 수집) 

   정식 명칭은 Web Scraping이며, 웹 사이트에서 원하는 정보를 추출하는 것을 의미합니다.
   보통 웹 사이트는 HTML기반이므로 정보를 추출할 페이지에서 개발자모드 실행 후

   원하는 태그를 검색하는 스킬이 요구됩니다.

웹 크롤링 라이브러리
1. Jsoup
   정적 데이터를 비교적 빠르게 수집할 수 있지만 브라우저가 아닌
   HTTP Request를 사용하기 때문에 동적 데이터를 수집하기 위해서는
   해당 서버의 인증키 요구 등 수집할 수 없는 경우가 많습니다.

2. Selenium
   Jsoup에 비해 느리지만 브라우저 드라이버를 사용하여 동적 데이터도 수집 가능합니다.

크롤링 환경 설치
   1. 브라우저 버전 확인(92버전)
      크롬 우측 메뉴 > 도움말 > 크롬 정보 > 버전 확인

   2. 크롬 드라이버 다운로드
      https://chromedriver.chromium.org/downloads
      맞는 버전 선택 후 다운로드 > C드라이브에 저장

   3. 셀레니움 서버 다운로드
      https://www.selenium.dev/downloads/

 

 

Downloads

Selenium automates browsers. That's it!

www.selenium.dev

 

 

ChromeDriver - WebDriver for Chrome - Downloads

Current Releases If you are using Chrome version 93, please download ChromeDriver 93.0.4577.15 If you are using Chrome version 92, please download ChromeDriver 92.0.4515.107 If you are using Chrome version 91, please download ChromeDriver 91.0.4472.101 For

chromedriver.chromium.org

 

마우스 우클릭-> Build Path를 통하여 jar파일을 추가해 줍니다.

 

package crawling;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class CGV {
	private WebDriver driver;
	public static final String WEB_DRIVER_ID = "webdriver.chrome.driver";
	public static final String WEB_DRIVER_PATH = "C:/chromedriver.exe";

	public static void main(String[] args) {
		CGV cgv = new CGV();
		WebElement movieDiv = null;
		int rank= 0;
		
		//해당 브라우저에 다양한 옵션을 주기위해 ChromeOptions 객체화
		ChromeOptions options = new ChromeOptions();
		//옵션 설정
		//headless : 브라우저 실행이 내부로 전환된다, 눈에 안보인다.
		options.addArguments("headless");
		
		//운영체제에 드라이버 설정
		System.setProperty(WEB_DRIVER_ID, WEB_DRIVER_PATH);
		
		//설정한 옵션 객체를 ChromeDriver 생성자를 통해 전달한다.
		cgv.driver = new ChromeDriver(options);
		
		options.setBinary("/path/to/other/chrome/binary");
		
		
		
		String url = "http://www.cgv.co.kr/movies/";

		//요청할 URL을 get()에 전달하면 응답된 페이지를 브라우저를 통해 확인할 수 있다.
		cgv.driver.get(url);
		try {
			//브라우저가 실행되는 시간을 기다려준다.
			Thread.sleep(1000);
		} catch (InterruptedException e) { // 자바가 셀레니움보다 빨라서 1초씩은 기다려줍니다. 브라우저 열리기도 전에 태그를 가져올수 있기떄문에
			e.printStackTrace();
		}

		// btn-more-fontbold : 더 보기 버튼 클래스 명
		//해당 URL에서 더 보기 버튼을 객체로 가져온 후 click()을 통해 클릭해준다.
		cgv.driver.findElement(By.className("btn-more-fontbold")).click(); 

		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		// sect-movie-chart : 영화 목록을 담고 있는 div 태그 클래스 명
		//div태그를 가져온 뒤 movieDiv에 넣어준다.
		movieDiv = cgv.driver.findElement(By.className("sect-movie-chart"));
		
		//div태그 안에 title클래스 태그를 전부 가져온다.(findElements())      
		for(WebElement el:movieDiv.findElements(By.className("title"))){
			//각각의 <strong class="title">태그를 el에 순서대로 담아준다.
			//가져온 태그안에 있는 내용(요소 , 컨텐츠, 텍스트)를 getText()로 가져올 수 있다.
			System.out.println(++rank+". "+el.getText());
		}

		cgv.driver.close();
		cgv.driver.quit();

	}
}
728x90
반응형

추천 글