[python] Selenium - 웹페이지 Alert창 다루기
#UnexpectedAlertPresentException #NoAlertPresentException 관련 정리 #Selenium Alert 다루기
웹페이지 크롤링이나 웹페이지 이벤트 테스트 작업을 진행하다보면 Aler창이 나옵니다.
일반적인 웹 페이지의 이동간 내용 확인과 오류를 사용자에게 알려주기 위해서 명시적으로 알림을 주는 창을 Alert이라고 합니다.
Selenium을 이용해 웹 크롤링이나 테스트를 하다 보면 Alert 창에 대한 처리를 중간중간 해줘야 하는 경우가 많습니다.
예기치 않은 알림 창들이 발생하면 테스트가 중단될 수 있는데, 이를 잘 처리하는 것이 중요합니다.
Selenium으로 웹크롤링이나 테스트 할 때 이러한 창을 처리하기 위해서 Exceprion을 이용해서 처리를 해야 합니다.
selenium은 이러한 처리를 위해 UnexpectedAlertPresentException 과 NoAlertPresentException 패키지를 제공합니다.
이번 포스팅에서는 Alert 창을 처리하는 다양한 Selenium 커맨드와 함께 예제 코드들도 소개해드릴게요! 😊
웹페이지 Alert창의 종류
1. 경고(alert) 창: 중요한 정보를 전달하거나 사용자의 주의를 요구합니다. 일반적으로 제목과 메시지가 포함되어 있으며, 사용자는 확인 버튼을 클릭하여 알림을 닫습니다.
2. 확인(confirm) 창: 사용자에게 작업 수행 여부를 확인하는 메시지를 표시합니다. 제목, 메시지, 확인 버튼 및 취소 버튼이 있으며, 사용자는 확인 또는 취소 버튼을 클릭하여 작업을 결정합니다.
3. 프롬프트(prompt) 창: 사용자로부터 추가 정보를 입력받기 위해 사용됩니다. 제목, 메시지, 입력 필드, 확인 버튼 및 취소 버튼이 있으며, 사용자는 입력 필드에 정보를 입력한 후 확인 또는 취소 버튼을 클릭하여 작업을 수행하거나 취소합니다.
4. 에러(error) 창: 오류 메시지를 표시하여 사용자에게 문제가 발생했음을 알립니다. 일반적으로 오류 메시지와 확인 버튼이 있으며, 사용자는 확인 버튼을 클릭하여 알림을 닫습니다.
Selenium Alert Handling 기본 명령 유형 (CommandType)
Selenium에서는 alert 창에 대하여 다음과 같이 "webdriver.CommandType" 을 제공하고 Alert창에 필요한 동작을 구현할 수 있습니다.
# webdriver.CommandType 의 종류
SendKeysToAlert: 경고창(alert)에 키를 보내는 동작
AcceptAlert: 경고창을 수락(확인)하는 동작
DismissAlert: 경고창을 거부(취소)하는 동작
SetAlertCredentials: 경고창의 인증 정보를 설정하는 동작
GetCurrentWindowHandle: 현재 창의 핸들을 가져오는 동작
GetWindowHandles: 모든 창 핸들을 가져오는 동작
SwitchToWindow: 다른 창으로 전환하는 동작
ㅁ Selenium Alert 다루기
Alert 창에 대하여 다음과 같은 방법을 취할 수 있습니다.
Alert창으로 포커스를 전환하고 Alert 창의 내용을 "확인" 또는"취소" 를 할 수 있습니다.
1. Alert Handling 기본 명령어
- alert = driver.switch_to.alert()
- alert.accept() # OK 버튼 클릭
- alert.dismiss() # Cancel 또는 닫기 버튼 클릭
- alert.text # Alert 창의 텍스트 가져오기
- alert.send_keys("입력 텍스트") # Alert 창의 입력란에 텍스트 입력하기
(2) 기본 명령어 사용법
# AcceptAlert : 경고창을 수락(확인)하는 동작 수행
alert = driver.switch_to.alert
alert.accept()
# DismissAlert: 경고창을 거부(취소)하는 동작 수행
alert = driver.switch_to.alert
alert.dismiss()
# SendKeysToAlert: 경고창에 키를 보내는 동작 수행
alert = driver.switch_to.alert
alert.send_keys("Hello, World!")
# GetCurrentWindowHandle: 현재 창의 핸들을 가져오는 동작 수행
current_handle = driver.current_window_handle
print("Current Window Handle:", current_handle)
# SwitchToWindow: 다른 창으로 전환하는 동작 수행
window_handle = "window_handle_to_switch" # 전환할 창의 핸들
driver.switch_to.window(window_handle)
2. UnexpectedAlertPresentException 으로 Alert 창 처리
UnexpectedAlertPresentException은 예기치 않은 알림이 나타나는 경우 발생하므로, 이를 미리 처리하는 코드를 작성해두는 것이 좋습니다.
from selenium.common.exceptions import UnexpectedAlertPresentException
try:
# 특정 작업 수행
button = driver.find_element_by_id('submit')
button.click() # 클릭 시 팝업 예상
except UnexpectedAlertPresentException:
print("Unexpected alert detected!")
alert = driver.switch_to.alert()
alert.accept() # 알림 창 닫기 및 확인
# 필요 시 추가 작업 진행
3. NoAlertPresentException 으로 Alert 처리
NoAlertPresentException은 예상되던 알림이 나타나지 않을 때 발생합니다. 이런 경우는 주로 타이밍 문제로 나타나며, 명시적 대기를 사용하여 이를 처리할 수 있습니다.
from selenium.common.exceptions import NoAlertPresentException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
try:
WebDriverWait(driver, 10).until(EC.alert_is_present()) # 10초 동안 알림 창 대기
alert = driver.switch_to.alert() # 알림 창 스위치
alert.accept() # 알림 창 확인
except NoAlertPresentException:
print("Alert not found!")
# 추가 작업 필요 시 작성
Selenium Alert 창을 만들고 닫는 예제
webdriver.CommandType.AcceptAlert 또는 webdriver.CommandType.DismissAlert 으로 Alert 창을 닫는 예시를 작성 했습니다.
from selenium import webdriver
from selenium.webdriver.common.alert import Alert
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoAlertPresentException
driver = webdriver.Chrome()
try:
driver.get('https://example.com/')
# 경고 창을 띄우는 동작 수행 : Javascript를 실행합니다.
driver.execute_script("alert('This is an alert!')")
# 경고 창이 있는지 확인
# alert_present = EC.alert_is_present()
alert_present = WebDriverWait(driver, 5).until(EC.alert_is_present())
if alert_present :
# 경고 창에 대해 switch_to.alert를 통해 액세스
alert = driver.switch_to.alert
# 경고 창을 거부(취소)하는 동작 수행
alert.dismiss()
print("Alert dismissed successfully!")
else:
print("Alert is not presented")
except NoAlertPresentException:
print("No alert found. Continuing with the script.")
except Exception as err:
print(" Exception {err=}, {type(err)=}")
finally:
driver.quit()
위의 예시는 Chrome 웹드라이버를 사용하여 웹 페이지에서 경고 창을 띄우고, webdriver.CommandType.DismissAlert 명령 유형을 사용하여 경고 창을 거부(취소)하는 동작을 수행하는 예시입니다.
코드를 실행하면 경고 창이 뜨고 이후에 자동으로 창이 닫히는 것을 확인할 수 있습니다.
- driver.execute_script("alert('This is an alert!')") : 열려있는 웹페이지에 JavaScrip를 실행해서 Alert 창을 엽니다.
- alert_present = EC.alert_is_present() 보다
- alert_present = WebDriverWait(driver, 5).until(EC.alert_is_present()) 가 유용하게 쓰이는 문장이 될 것 같습니다.
- WebDriverWait(driver, 5) 은 5초 동안 alert이 출력되지 않으면 다음으로 넘어 가도록 합니다.
'Programming' 카테고리의 다른 글
Rust기초 알기 - 3.3 함수 정의와 호출 (7) | 2023.06.18 |
---|---|
Rust기초 알기 - 3.2 제어문 (조건문, 반복문) (21) | 2023.06.14 |
Rust기초 알기 - 3.1 변수와 데이터 타입 (9) | 2023.06.06 |
Rust기초 알기 - 2.3 Rust 개발 IDE에디터 소개 (7) | 2023.05.28 |
[python] Selenium 에서 접하는 Wait 정리 - implicitly wait explicitly wait 이해 (20) | 2023.05.25 |
Rust 기초 알기 - 2.2 Rust 개발 도구 소개 (16) | 2023.05.24 |
Rust 기초 알기 - 2.1 Rust 설치 (6) | 2023.05.20 |