반응형
소개
Selenium을 사용하다가 웹 페이지에서 예기치 않은 경고(Alert)가 표시되는 경우, 'UnexpectedAlertOpenException' 오류가 발생할 수 있습니다. 이 에러는 Selenium이 작업을 수행하려고 할 때 경고가 열리면서 발생합니다. 이 블로그에서는 이 오류의 원인과 해결 방법에 대해 알아보겠습니다.
에러 발생 예시 코드
먼저, 'UnexpectedAlertOpenException' 오류가 발생할 수 있는 간단한 예시 코드를 살펴봅시다.
from selenium import webdriver
# 웹드라이버 설정
driver = webdriver.Chrome()
# 특정 웹사이트로 이동
driver.get('http://example.com')
# 웹사이트에서 특정 작업 수행 (예: 버튼 클릭)
button = driver.find_element_by_id('alertButton')
button.click()
# 경고(alert) 창이 나타날 경우에 대해 고려하지 않고 계속 진행
input_field = driver.find_element_by_id('inputField')
input_field.send_keys('Hello World!')
에러 해결 방법
1. Alert를 수동으로 처리하기
경고(alert)가 열리면 Selenium은 대기되지 않고 다음 명령어로 진행하려고 하므로, 수동으로 경고를 처리하는 것이 필요합니다.
from selenium import webdriver
from selenium.common.exceptions import UnexpectedAlertPresentException, NoAlertPresentException
# 웹드라이버 설정
driver = webdriver.Chrome()
try:
# 특정 웹사이트로 이동
driver.get('http://example.com')
# 웹사이트에서 특정 작업 수행
button = driver.find_element_by_id('alertButton')
button.click()
# 경고를 기다리기
alert = driver.switch_to.alert
alert.accept() # 경고 수락
except UnexpectedAlertPresentException:
print("예기치 않은 경고가 발생하였습니다!")
except NoAlertPresentException:
print("경고가 없습니다.")
```
2. 경고에 대한 자동 대기 설정하기
Selenium의 WebDriverWait를 사용하여 경고가 나타날 때까지 대기할 수 있습니다. 이렇게 하면 경고가 생겼을 때에 대한 대비를 할 수 있습니다.
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
# 웹드라이버 설정
driver = webdriver.Chrome()
# 특정 웹사이트로 이동
driver.get('http://example.com')
# 웹사이트에서 특정 작업 수행
button = driver.find_element_by_id('alertButton')
button.click()
try:
# 경고가 나타날 때까지 최대 10초 대기
WebDriverWait(driver, 10).until(EC.alert_is_present())
alert = driver.switch_to.alert
alert.accept() # 경고 수락
except TimeoutException:
print("경고가 나타나지 않았습니다.")
마무리
이 블로그 글에서는 Selenium에서 발생하는 'UnexpectedAlertOpenException' 오류에 대한 간단한 해결 방법을 살펴보았습니다. 경고를 수동으로 처리하거나, WebDriverWait을 사용하여 경고가 나타날 때까지 대기함으로써 이 문제를 해결할 수 있습니다. 자동화 작업을 할 때는 항상 예기치 않은 상황에 대비하기 위해 경고 처리를 고려해야 합니다.
반응형
'Python > Selenium' 카테고리의 다른 글
Selenium의 명시적 대기 (Explicit Wait) 사용하기 (0) | 2025.02.13 |
---|---|
Selenium UnknownServerError 오류 해결하기 (0) | 2025.02.12 |
Selenium UnableToSetCookieException 오류 해결하기 (0) | 2025.02.12 |
Select 클래스를 이용한 드롭다운 메뉴 자동화 (0) | 2025.02.12 |
예상 조건을 이용한 Selenium 대기 전략 (0) | 2025.02.12 |