반응형
Python과 Selenium을 결합하면 브라우저를 마치 사람처럼 제어해 복잡한 웹 페이지에서 자동으로 데이터를 수집할 수 있습니다. 이 튜토리얼에서는 셀레니움의 기본 설치부터 핵심 메서드 활용 예제, 그리고 간단한 뉴스 기사 크롤링 예제까지 단계별로 살펴봅니다. 코드를 직접 실행하며 웹 크롤링 자동화의 원리를 익혀 보세요.
1. 개발 환경 설정
Selenium을 사용하기 위해서는 Python(3.7 이상 권장)과 웹드라이버(ChromeDriver 등)가 필요합니다.
- Python 설치: python.org에서 운영체제에 맞는 버전을 다운로드 후 설치합니다.
- Selenium 패키지 설치:
pip install selenium
- ChromeDriver 다운로드: ChromeDriver를 공식 사이트에서 내려받고, 시스템 환경 변수(PATH)에 추가합니다.
2. 브라우저 실행 및 간단 스크립트
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://www.naver.com")
print(driver.title)
driver.quit()
3. 요소 찾기(find element)
- ID 선택:
driver.find_element("id", "search-input")
- CSS 선택자:
driver.find_element("css selector", ".btn_search")
- XPath:
driver.find_element("xpath", "//a[text()='뉴스']")
4. 대기 처리
암묵적 대기:
driver.implicitly_wait(10)
명시적 대기:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
elem = wait.until(EC.presence_of_element_located((By.ID, "content")))
5. 폼 입력과 클릭
search_box = driver.find_element("name", "query")
search_box.send_keys("파이썬 셀레니움")
search_btn = driver.find_element("css selector", ".search_btn")
search_btn.click()
6. 스크린샷 및 페이지 소스
driver.save_screenshot("screenshot.png")
html = driver.page_source
print(html[:200])
7. 실전 예제: 뉴스 기사 제목 크롤링
driver.get("https://news.naver.com")
articles = driver.find_elements("css selector", "div.cluster_body a.cluster_text_headline")
for a in articles:
title = a.text
link = a.get_attribute("href")
print(title, link)
8. 자동화 팁
- 헤드리스 모드: 브라우저 창 없이 실행
- 브라우저 옵션: 사용자 에이전트 변경, 창 크기 지정
- 예외 처리:
NoSuchElementException
잡기 - 로그 기록: 크롤링 과정 기록으로 디버깅 편의성 향상
최종 요약
이 글에서 살펴본 파이썬 셀레니움 기본 사용법은 웹 브라우저 제어, 요소 선택, 대기 처리, 폼 입력, 스크린샷, 그리고 간단한 뉴스 기사 크롤링까지를 포함합니다. 직접 예제 코드를 실행하며 단계별로 기능을 이해하고, 사이트 구조에 맞춰 응용해 보세요. 반복 연습과 로그 확인을 통해 자동화 스크립트의 안정성을 높이면, 복잡한 웹 크롤링 작업도 손쉽게 처리할 수 있습니다.
반응형