본문 바로가기
Python/Selenium

Selenium NoAlertPresentException 오류 해결하기

by PySun 2025. 1. 5.
반응형

소개

Selenium을 사용하다 보면 'NoAlertPresentException' 오류에 직면하게 될 수 있습니다. 이 오류는 현재 웹 페이지에 알림이 없거나, 알림을 처리할 수 없는 상태에서 알림을 호출하려 할 때 발생합니다. 이 글에서는 이 오류가 발생하는 주된 원인과 그것을 해결할 수 있는 방법을 알아보겠습니다.

에러 발생 예시 코드

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

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

# 웹 드라이버 초기화
driver = webdriver.Chrome()

# 특정 URL 열기
driver.get("https://example.com")

# 알림 접속 시도
try:
    alert = driver.switch_to.alert
    alert.accept()
except NoAlertPresentException:
    print("현재 활성화된 알림이 없습니다.")

# 웹 드라이버 종료
driver.quit()

에러 해결 방법

1. 알림이 존재하는지 먼저 확인하기

알림이 존재하는지 확인하지 않고 접근하려 할 경우 오류가 발생할 수 있습니다. 따라서 알림이 존재하는지 확인하는 것이 첫 번째로 중요합니다.

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

# 웹 드라이버 초기화
driver = webdriver.Chrome()

# 특정 URL 열기
driver.get("https://example.com")

# 알림 확인 후 처리
try:
    # 알림이 있는지 확인
    alert_present = driver.switch_to.alert
    alert_present.accept()
except NoAlertPresentException:
    print("현재 활성화된 알림이 없습니다.")

# 웹 드라이버 종료
driver.quit()

2. 적절한 대기 시간 설정

웹 페이지의 요소들이 로드되고 알림이 나타날 시간을 고려해야 합니다. 이를 위해 적절한 대기 시간을 설정하여 프로세스를 조정할 수 있습니다.

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

# 웹 드라이버 초기화
driver = webdriver.Chrome()

# 특정 URL 열기
driver.get("https://example.com")

# 페이지가 로드될 때까지 대기
time.sleep(5)  # 여기서 적절한 시간을 조정하세요

# 알림 확인 후 처리
try:
    alert = driver.switch_to.alert
    alert.accept()
except NoAlertPresentException:
    print("현재 활성화된 알림이 없습니다.")

# 웹 드라이버 종료
driver.quit()

마무리

이 블로그 글에서는 Selenium에서 발생하는 'NoAlertPresentException' 오류에 대해 살펴보았습니다. 알림이 존재하는지 먼저 확인하고, 적절한 대기 시간을 설정함으로써 이 문제를 해결할 수 있습니다. Selenium을 사용할 때는 언제나 페이지의 로드 시간이나 동적인 요소를 고려하여 안정적인 테스트 환경을 구축하는 것이 중요합니다.

반응형