Crawling 중 데이터 불러오는 과정 중 생긴 문제 해결 - LikeLionTeam/BootHouse GitHub Wiki

✔상황

  • 크롤링을 할 때, url을 카테고리별로 나눠 진행하였기 때문에 모든 데이터가 아닌 해당 카테고리에 해당되는 데이터만이 크롤링 되어야 하지만 모든 데이터를 불러오는 문제 발생

    (예, 전체 부트캠프 개수 : 250 , 웹 카테고리 개수: 50 → 50개의 데이터가 불러와지는 것이 정상 but 250개가 불러와짐)

  • 아무 코드도 건들이지 않은 상황에서 갑자기 아예 모든 데이터를 불러오지 못하는 문제 발생

✔문제 발생

1. 충분한 로딩 시간 부족

기존 코드에서는 최초 페이지가 로드되는 부분에만 WebDriverWait 을 사용하여 지정한 요소가 로드되기까지 기다리도록 작성하였으나, 대기 코드 부족 및 특정 요소 로딩이 되지 않음

//최대 10초까지 대기
WebDriverWait wait = new WebDriverWait(webDriver, Duration.ofSeconds(10));

// i번째 부트캠프의 상세페이지에 접속
WebElement detailButton = element.findElement(By.cssSelector("a"));
String hrefValue = detailButton.getAttribute("href");
webDriver.get(hrefValue);

// 상세 페이지가 완전히 로드될 때 까지 대기
wait.until(ExpectedConditions.presenceOfElementLocated(By.tagName("html")));

문제점: 로드될 때까지의 코드 개수가 적고, wait 코드가 제대로 작동하지 않음.

2. 셀레니움 내부의 크롬창 크기 변경

//부트캠프들의 리스트를 찾아옴
List<WebElement> elements = webDriver.findElements(By.cssSelector("body > main > section > div:nth-child(5) > div > section > ul > li" ));

문제점: 크롬창의 크기가 변경되면 내부 HTML 태그들의 변화로 인해 경로가 변경됨 → cssSelector를 찾지 못해 데이터를 가져오지 못하는 문제 발생.

✔해결 과정

1-1. Thread.sleep 대신 WebDriverWait 사용

  • 처음에는 Thread.sleep을 통해 대기 시간을 확보하는 방식 사용 → 무조건 지정된 시간만큼 대기하기 때문에 비효율적인 해결 방식임을 인지.
  • Thread.sleep을 제거하고, WebDriverWait을 활용하여 특정 요소가 나타날 때까지 대기하도록 수정.

1-2. 대기 코드 추가

  • 여러 요소가 로드되는 과정에서 WebDriverWait을 적절히 활용하여 대기 시간 확보.

2. 창 크기 고정 코드 추가

  • 크롬 창 크기가 변하지 않도록 고정하여 HTML 구조 변화를 방지.

주요 해결 코드:

1. WebDriverWait 적용 및 대기 코드 추가

// Thread.sleep(2000); 비효율적 문제 해결 방식
WebDriverWait wait = new WebDriverWait(webDriver, Duration.ofSeconds(10));

// 카테고리별 url에 접속
webDriver.get(urlArray[j]);
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("body")));

//부트캠프들의 리스트를 찾아옴
List<WebElement> elements = webDriver.findElements(By.cssSelector("body > main > section > div:nth-child(5) > div > section > ul > li" ));

for (int i = 0; i < elements.size(); i++) {
    try {
        // i번째 부트캠프 찾아옴
        WebElement element = elements.get(i);

        // i번째 부트캠프의 상세페이지에 접속
        WebElement detailButton = element.findElement(By.cssSelector("a"));
        String hrefValue = detailButton.getAttribute("href");
        webDriver.get(hrefValue);

        wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("body")));

        // 크롤링 진행 후 원래 페이지로 돌아가기
        webDriver.navigate().back();
        wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("body")));
    } catch (NoSuchElementException e) {
        System.out.println("요소를 찾을 수 없음: " + e.getMessage());
        continue;
    }
}

2. 초기 설정 시 크롬 창 고정

ChromeOptions options = new ChromeOptions();
options.addArguments("--window-size=1000,800");
options.addArguments("--start-maximized");

✔정리

  • 페이지 로딩 시 WebDriverWait을 활용하여 충분한 대기시간 확보!
  • 창 크기에 따라 HTML 구조가 변하는 경우 창 크기 고정 설정 필수!
  • 예외 처리를 추가하여 크롤링이 중단되지 않도록 방어 코드 적용!
⚠️ **GitHub.com Fallback** ⚠️