본문 바로가기
Artificial Intelligence/60. Python

[PYTHON] Selenium으로 웹을 자동화하는 모든 방법

by Papa Martino V 2025. 7. 22.
728x90

Selenium으로 웹을 자동화하는 모든 방법
[PYTHON] Selenium

 

웹 페이지를 자동으로 제어하고 데이터를 추출하거나 테스트를 수행하고 싶다면 Selenium은 최고의 선택입니다. 특히 Python과 함께 사용할 때, 간결하고 직관적인 코드로 브라우저를 자유자재로 다룰 수 있습니다. 이 글에서는 Selenium의 핵심 기능과 실무 활용 사례를 중심으로 전문적인 웹 자동화 전략을 소개합니다.

1. Selenium이란?

Selenium은 웹 브라우저를 자동으로 제어할 수 있도록 도와주는 오픈소스 프레임워크입니다. 주로 테스트 자동화, 웹 크롤링, 반복 작업 자동화에 사용되며, Chrome, Firefox, Edge 등 다양한 브라우저와 호환됩니다.

2. 설치 방법 및 기본 설정


pip install selenium

설치 후, 브라우저 드라이버(ex. ChromeDriver)를 다운로드 받아 시스템 경로에 추가하거나 실행 경로에 배치해야 합니다.

3. 기본 코드 구조


from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service

# 크롬 드라이버 경로 설정
service = Service("chromedriver 경로")
driver = webdriver.Chrome(service=service)

driver.get("https://example.com")
print(driver.title)
driver.quit()

4. 주요 기능 요약

기능 설명 예시 코드
페이지 이동 URL로 직접 이동 driver.get("URL")
요소 찾기 HTML 요소 탐색 driver.find_element(By.ID, "id")
입력하기 텍스트 입력 element.send_keys("text")
클릭 버튼 클릭 element.click()
스크린샷 화면 저장 driver.save_screenshot("shot.png")

5. 웹 크롤링 실전 예제

Selenium을 이용하여 뉴스 사이트의 제목을 수집하는 코드 예시입니다.


from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get("https://news.ycombinator.com/")

titles = driver.find_elements(By.CLASS_NAME, "titleline")

for title in titles:
    print(title.text)

driver.quit()

6. 동적 콘텐츠 처리 (JavaScript 렌더링)

BeautifulSoup 등 정적 크롤링 도구와 달리, Selenium은 JavaScript로 렌더링되는 동적 페이지도 쉽게 처리할 수 있습니다.


import time
driver.get("https://example.com")
time.sleep(3)  # JavaScript 로딩 대기

7. 자동 로그인 구현

웹사이트에 자동 로그인하는 간단한 코드입니다.


driver.get("https://login.example.com")
driver.find_element(By.ID, "username").send_keys("myID")
driver.find_element(By.ID, "password").send_keys("myPassword")
driver.find_element(By.ID, "submit").click()

8. 테스트 자동화 활용

Selenium은 단위 테스트 프레임워크와 함께 사용하여 UI 테스트 자동화를 수행할 수 있습니다. 예:


import unittest

class UITest(unittest.TestCase):
    def test_title(self):
        driver = webdriver.Chrome()
        driver.get("https://example.com")
        self.assertEqual("Example Domain", driver.title)
        driver.quit()

9. Headless 모드

브라우저 창을 띄우지 않고 백그라운드에서 작업을 수행할 수 있습니다.


from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument("--headless")
driver = webdriver.Chrome(options=options)

10. Selenium vs BeautifulSoup vs Scrapy

항목 Selenium BeautifulSoup Scrapy
기반 브라우저 제어 HTML 파싱 크롤링 프레임워크
속도 느림 빠름 매우 빠름
동적 페이지 가능 불가 제한적
사용 난이도 중간 쉬움 복잡함

11. 실무에서 유용한 팁

  • 예외 처리 필수 (NoSuchElementException 등)
  • WebDriverWait를 활용한 안정적 대기
  • 반복 크롤링 시 User-Agent 변경 및 IP 로테이션 권장
  • Headless 모드 + Docker로 자동화 배포 가능

12. 결론: Selenium은 웹 자동화의 강력한 동반자

Selenium은 단순한 크롤러를 넘어 웹 테스트 및 자동화의 핵심 도구로 자리 잡고 있습니다. 특히 Python과의 궁합은 뛰어나며, GUI 자동화, 브라우저 자동 제어, 데이터 수집 등 광범위한 작업에 적합합니다. 본 가이드를 통해 Selenium의 다양한 기능을 실무에 적극 활용해보세요.

참고 출처

728x90