이전에 Selenium 설정을 진행해보았다.

 

설정을 완료하였으니 직접 사용해보자.

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

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.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class CrawlingTest2 {
	public static ArrayList<TestDTO> crawling() {
		ArrayList<TestDTO> Test_data = new ArrayList<TestDTO>();;

		// 1. WebDriver와 ChromeDriver 설정
		// 프로젝트 폴더 기준으로 chromedirver.exe 파일의 위치를 작성
		//System.setProperty("webdriver.chrome.driver", "driver/chromedriver.exe");
		//최신 Selenium 에서 는 자동으로 크롬 드라이버를 찾아준다.
		WebDriver driver = new ChromeDriver();

		// 주소 설정
		String url = "https://spiri7.com/store/category?category=2";

		// 웹 페이지 접속
		driver.get(url);
		
		// 현재 ChromeDriver의 대기 시간 10초를 부여
		WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
		
		// 상품의 a태그를 불러오자.
		List<WebElement> links = driver.findElements(By.cssSelector(".flex-wrap > a"));

		//데이터가 있는지 없는지 비교
		System.out.println(!links.isEmpty());
		if(!links.isEmpty()) {
			//있으면 해당 요소 만큼 for문을 돌린다
			for (WebElement webElement : links) {
				// a 태그의 href : 주소를 불러온다. 
				String link = webElement.getAttribute("href");
				
				//넘어간 주소를 확인
				System.out.println("주소 : "+link);
				
				//불러온 주소로 이동
				driver.get(link);
				
				//부여된 대기시간 만큼 웹 로딩을 기다리고 KoPubWorldDotum 클래스 > h1 태그가 불러올 때까지 대기
				wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".font-KoPubWorldDotum > h1")));
				
				// KoPubWorldDotum 클래스 > h1 태그가 있는 정보를 모두 불러온다
				List<WebElement> elements_title = driver.findElements(By.cssSelector(".font-KoPubWorldDotum > h1"));
				List<WebElement> elements_sal = driver.findElements(By.cssSelector(".font-KoPubWorldDotum > div > div.text-red-400.text-xl.font-bold.truncate"));
				
				//있으면 해당 요소 만큼 for문을 돌린다
				for(WebElement webElement2:elements_title) {
					//불러온 태그 요소의 글자만 가져오고 
					String title = webElement2.getText();
					//TestDTO에 값을 저장
					TestDTO data = new TestDTO();
					//상품을 저장하고
					data.setTitle(title);
					//상품의 대한 가격을 추가해줍니다.
					data.setPrice(Integer.parseInt(elements_sal.get(0).getText().replace(",", "").replace("원신규회원", "")));
					//DAO에 추가로 저장해둔다.
					Test_data.add(data);
					System.out.println("webElement2 : "+ title + " : "+ elements_sal.get(0).getText().replace(",", "").replace("원신규회원", ""));
				}
				//이전 페이지로 전환
				driver.navigate().back();
			}
		}

		//드라이버 종료
		driver.quit();
		return Test_data;
	}

	public static void main(String[] args) {
		ArrayList<TestDTO> datas = CrawlingTest2.crawling();
		System.out.println(datas); 
	}
}

 

이번 팀 프로젝트에서 클라이밍 상점페이지를 제작할때 

임시 데이터를 가져올 연습을 진행해 보았다.

위 코드를 실행하면 아래 내용처럼 주소 상품명, 상품이 출력되는 것을 확인할 수 있다.

주소 : https://spiri7.com/goods/87

webElement2 : 인스팅트 VSR : 220875

주소 : https://spiri7.com/goods/88

webElement2 : 스콰마 skwama : 222735

주소 : https://spiri7.com/goods/94

webElement2 : 플래그십 : 222270

주소 : https://spiri7.com/goods/31

webElement2 : 문다카 : 116250

주소 : https://spiri7.com/goods/183

webElement2 : 인달로 Indalo : 204600

주소 : https://spiri7.com/goods/93

webElement2 : TN Pro 티엔프로 : 212970

주소 : https://spiri7.com/goods/14

webElement2 : 드라고 LV : 220875

주소 : https://spiri7.com/goods/290

webElement2 : 수드업 Souped up : 222270

주소 : https://spiri7.com/goods/34

webElement2 : 오아시 : 182280

주소 : https://spiri7.com/goods/97

webElement2 : 탄타 : 119040

 

728x90
개발자가 되고 싶은 곰