본문 바로가기
Python/Selenium

selenium UnhandledAlertException 오류 해결하기

by PySun 2025. 1. 30.
반응형

소개

Selenium을 사용하다가 'UnhandledAlertException' 오류에 봉착하는 경우는 꽤 흔한 문제입니다. 이 오류는 브라우저에서 떠 있는 경고(alert) 창을 무시하려 할 때 발생합니다. 이 블로그 글에서는 'UnhandledAlertException' 오류가 발생하는 원인과 해결 방법에 대해 알아보겠습니다.

에러 발생 예시 코드

먼저, 'UnhandledAlertException' 오류가 발생할 가능성이 있는 간단한 코드 예시를 살펴봅시다.

from selenium import webdriver

# 브라우저 드라이버 초기화
driver = webdriver.Chrome()

# 특정 웹사이트 접속
driver.get('http://example.com')

# 경고창 없이 일부 작업 수행
driver.find_element_by_id('some_element').click()  # 경고가 발생할 수 있는 클릭

에러 해결 방법

1. 경고창 처리하기

먼저, 'UnhandledAlertException' 오류를 피하기 위해서는 경고창을 처리하는 것이 중요합니다. 이를 위해 Selenium의 `switch_to.alert`를 사용할 수 있습니다.

from selenium import webdriver
from selenium.common.exceptions import NoAlertPresentException

driver = webdriver.Chrome()
driver.get('http://example.com')

try:
    # 경고창이 떠 있을 때 그것을 처리
    alert = driver.switch_to.alert
    alert.accept()  # 경고창 수락
except NoAlertPresentException:
    print("경고창이 없습니다. 다른 작업을 진행합니다.")

# 경고창이 처리된 후 계속 작업 수행
driver.find_element_by_id('some_element').click()

2. 경고창 무시하기

경고창을 무시하고 작업을 계속하려면, 예외를 처리하는 방법도 있습니다. 아래의 코드처럼 예외를 try-except 블록으로 감싸주면 됩니다.

from selenium import webdriver
from selenium.common.exceptions import UnhandledAlertException

driver = webdriver.Chrome()
driver.get('http://example.com')

try:
    driver.find_element_by_id('some_element').click()
except UnhandledAlertException as e:
    print("경고창이 무시되었습니다:", e)

# 그 후에 다른 작업 진행

마무리

이번 블로그 글에서는 Selenium을 사용할 때 발생할 수 있는 'UnhandledAlertException' 오류의 기본 원인 및 해결 방안에 대해 알아보았습니다. 경고창을 적절히 처리하거나 무시함으로써 라이브러리 사용의 흐름을 방해받지 않도록 하는 것이 중요합니다. 항상 웹 자동화를 진행할 때는 테스트 환경에서 충분히 검토한 후에 실제 운영에 적용하세요!

반응형