본문 바로가기
카테고리 없음

파이썬 Selenium UnexpectedAlertPresentException 오류 해결하기

by PySun 2023. 8. 30.
반응형

UnexpectedAlertPresentException은 예기치 않은 경고창이 나타났을 때 발생하는 예외입니다. 이 예외는 경고창이 예상치 못한 타이밍에 나타날 때 발생할 수 있습니다. 예시 코드와 해결 방법에 대해 설명하겠습니다.

예시 코드:

아래 예시 코드에서는 UnexpectedAlertPresentException이 발생할 수 있는 상황을 보여줍니다. 예상치 못한 경고창이 나타났을 때 예외가 발생하는 시나리오를 시뮬레이션한 것입니다.

from selenium import webdriver
from selenium.common.exceptions import UnexpectedAlertPresentException

try:
    driver = webdriver.Chrome('path/to/chromedriver')

    # 예상치 못한 경고창이 나타날 수 있는 상황 시뮬레이션
    driver.get('https://www.example.com')
    driver.execute_script("alert('Unexpected alert!');")

except UnexpectedAlertPresentException as e:
    print("UnexpectedAlertPresentException이 발생했습니다:", str(e))
finally:
    # 브라우저 종료
    driver.quit()

해결 방법:

UnexpectedAlertPresentException이 발생한 경우 다음과 같은 방법으로 처리할 수 있습니다.

Alert 다루기:

경고창을 확인하고 처리하는 방법을 사용하여 예상치 못한 경고창을 처리합니다. Selenium의 Alert 클래스를 사용하여 경고창을 다루고 확인 또는 취소 버튼을 누릅니다.

from selenium.webdriver.common.alert import Alert

# 경고창 다루기 예시
alert = Alert(driver)
alert.accept()  # 확인 버튼 누르기

브라우저 다시 시작:

UnexpectedAlertPresentException이 발생한 경우 브라우저를 종료하고 다시 시작하여 초기 상태로 돌아갈 수 있습니다.

# 브라우저 다시 시작 예시
driver.quit()
driver = webdriver.Chrome('path/to/chromedriver')
driver.get('https://www.example.com')

Alert 대기 및 확인:

예상치 못한 경고창이 나타날 때까지 대기하고, 경고창이 나타난 후 처리합니다.

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# Alert 대기 및 확인 예시
driver.get('https://www.example.com')
wait = WebDriverWait(driver, 10)
wait.until(EC.alert_is_present())
alert = Alert(driver)
alert.accept()  # 경고창 확인

UnexpectedAlertPresentException이 발생한 경우, 경고창을 처리하거나 브라우저를 재시작하여 문제를 해결합니다. 또한 WebDriverWait를 사용하여 경고창이 나타날 때까지 대기하고 처리할 수 있는 방법을 고려해볼 수도 있습니다.

반응형