본문 바로가기
Python/Selenium

Selenium SeleniumException 오류 해결하기

by PySun 2025. 2. 3.
반응형

소개

Selenium을 사용하다 보면 'SeleniumException' 오류에 부딪힐 수 있습니다. 이 오류는 다양한 원인으로 발생할 수 있으며, 그에 따라 적절한 해결책이 필요합니다. 이 블로그 글에서는 'SeleniumException' 오류의 원인과 이를 해결하는 방법을 알아보겠습니다.

에러 발생 예시 코드

먼저, 'SeleniumException' 오류가 발생할 수 있는 간단한 예시 코드를 살펴보겠습니다.

from selenium import webdriver
from selenium.common.exceptions import SeleniumException

# 브라우저 열기
driver = webdriver.Chrome()

try:
    # 잘못된 URL을 입력하여 예외 발생
    driver.get("htp://example.com")
except SeleniumException as e:
    print(f"에러 발생: {e}")

driver.quit()

에러 해결 방법

1. URL 형식 확인하기

Selenium에서 URL을 입력할 때, URL 형식이 올바른지 확인하는 것이 중요합니다. 'htp'는 'http'로 수정해야 합니다.

from selenium import webdriver
from selenium.common.exceptions import SeleniumException

# 브라우저 열기
driver = webdriver.Chrome()

try:
    # 올바른 URL로 수정
    driver.get("http://example.com")
except SeleniumException as e:
    print(f"에러 발생: {e}")

driver.quit()

2. 웹드라이버 설치 상태 확인하기

Selenium은 각 브라우저에 대한 웹드라이버가 필요합니다. 해당 웹드라이버가 설치되어 있고, 작업 중인 브라우저 버전과 호환되는지 확인하세요. 예를 들어, Chrome 브라우저를 사용하는 경우 ChromeDriver가 필요합니다.

from selenium import webdriver

# 웹드라이버가 환경 변수에 등록되어 있는지 확인
try:
    driver = webdriver.Chrome()
except Exception as e:
    print(f"웹드라이버를 실행할 수 없습니다: {e}")

3. 웹 페이지 로딩 대기하기

웹 페이지가 완전히 로드되지 않았는데 요소에 접근하려고 할 때도 'SeleniumException'이 발생할 수 있습니다. 이 경우, 'WebDriverWait'을 사용해 페이지가 로드될 때까지 대기할 수 있습니다.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 브라우저 열기
driver = webdriver.Chrome()

# 올바른 URL로 접속
driver.get("http://example.com")

try:
    # 특정 요소가 로드될 때까지 대기
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "exampleElementId"))
    )
    print("요소가 로드되었습니다.")
except SeleniumException as e:
    print(f"에러 발생: {e}")

driver.quit()

마무리

이 블로그 글에서는 'SeleniumException' 오류의 일반적인 원인과 해결 방법을 살펴보았습니다. URL 형식을 확인하고, 웹드라이버의 설치 상태를 점검하며, 페이지 로딩을 기다리는 방법을 통해 이러한 문제를 효과적으로 해결할 수 있습니다. Selenium을 사용할 때는 이러한 오류를 유연하게 대처하는 방법을 기억하고, 개발 환경 세팅 및 요구 사항을 항상 점검하는 것이 중요합니다.

반응형