Python Selenium alert 여부 - Python Selenium alert yeobu

Selenium에서 어떤 브라우저를 사용하는지, 그리고 어떤 버전을 사용하는지에 따라서 다릅니다.

(구글링해보니 지원하지 않는 것도 있다고 하네요.)

우선 다음과 같은 방법이 권장됩니다.


driver.switch_to.alert.accept()


참고로 driver.switch_to_alert().accept()는 deprecated 되었습니다.

위에 방법으로 안 되는 경우에는 아래와 같이 해보세요 ^^


from selenium.webdriver.common.alert import Alert

    Alert(driver).accept()


참고로 다음과 같은 방법으로 원천적으로 alert 창이 뜨지 않도록 할 수 있습니다(파폭 기준).


options.set_preference('dom.webnotifications.enabled', False)

또는 options.set_preference("dom.push.enabled", False)


그런데 제가 테스트를 해보니 첫번째 방법으로는 모든 alert 창이 뜨지 않는 것은 아니네요.

(두번째 방법은 아직 테스트를 하지 못했습니다.)

selenium 이용시 Alert을 제어하는 방법

selenium으로 크롤링 진행하다보면 Alert을 제어해야 하는 경우가 있다.

( Alert이 떴을 때 제어하지 않고 작업을 진행하면 UnexpectedAlertPresentException 이 발생 )

3가지 타입의 Alert 제어 하는 방법을 알아보자

[ 3가지 타입의 Alert ]

1. Alert 창 선택

from selenium import webdriver
from selenium.webdriver.common.alert import Alert

URL = '진입할 주소'

driver = webdriver.Chrome('chromedriver.exe')
driver.get(URL)

da = Alert(driver) 

# 코드 해석

 - 2. Alert import

 - 9. da에 Alert 객체 할당

2. Alert 기본 제어

# 확인을 누른다.
da.accept()

# 창을 닫는다.
da.dismiss()

# 창의 text를 얻어온다.
da.text

# 코드 해석

 - 주석 참고

3. Prompt 제어

 - Alert, Confirm은 확인과 취소만 하면 되지만 Prompt는 값을 입력해주어야 한다.

 값 입력 방법은 아래와 같다. 입력한 값이 화면에 보이지는 않지만 정상적으로 입력이 된다.

# 값 입력 함수
da.send_keys('prompt에 값을 입력')

# 코드 해석

 - 주석 참고

이상 Alert 제어하는 간단한 방법 설명을 마친다.

[ 관련 글 보기 ]

2018/02/11 - [Python] - [파이썬 크롤링] selenium을 이용해 크롤링하기1 (크롬 실행)

2018/02/11 - [Python] - [파이썬 크롤링] selenium을 이용해 크롤링하기2 (데이터 가져오기)

2018/02/12 - [Python] - [파이썬 크롤링] selenium을 이용해 크롤링하기3 (자바스크립트 사용)

don't stop believing

Alert 창 처리에 대해 확인해 보겠습니다.

우선 아래와 같이 html 파일을 만들었습니다.

<!DOCTYPE html>
<html>
<script>
	function simpleAlert() {
		alert("Hello! I am a simple alert box!");
	}

	function confirmAlert() {
		var txt;
		var r = confirm("Press a button!\nEither OK or Cancel.\nThe button you pressed will be displayed in the result window.");
		if (r == true) {
			txt = "You pressed OK!";
		} else {
			txt = "You pressed Cancel!";
		}
		document.getElementById("confirmMemo").innerHTML = txt;
	}

	function promptAlert() {
		var person = prompt("Please enter your name", "Harry Potter");
		if (person != null) {
			document.getElementById("inputMemo").innerHTML = "Hello " + person + "! How are you today?";
		}
	}
</script>

<body>

<p>Click the button to display a simple alert box.</p>
<button onclick="simpleAlert()" id="simpleAlert">Try it</button>


<p>Click the button to demonstrate line-breaks in a confirm box.</p>
<button onclick="confirmAlert()" id="confirmAlert">Try it</button>
<p id="confirmMemo"></p>


<p>Click the button to demonstrate the prompt box.</p>
<button onclick="promptAlert()" id="promptAlert">Try it</button>
<p id="inputMemo"></p>

</body>
</html>

실행하면 세개의 Try it 버튼이 있습니다. 

python selenium으로 위 Alert 창을 처리하는 script 입니다.

WebDriver로 Alert 창을 Control하고 싶다면 switch_to.alert를 사용하면 됩니다

# -*- coding: utf-8 -*-
import time
from selenium import webdriver

# Chrome WebDriver를 이용해 Chrome을 실행합니다.
driver = webdriver.Chrome('./../chromedriver')

# pop.html 파일을 실행합니다.
driver.get('file:///Users/tongchunkim/Documents/Test_Selenium/alert_pop/pop.html')
time.sleep(2)

# 첫 번째 alert 버튼을 클릭합니다.
inputElement = driver.find_element_by_id('simpleAlert')
inputElement.click()
time.sleep(2)

# alert 창의 '확인'을 클릭합니다.
alert = driver.switch_to.alert
alert.accept()
time.sleep(2)

# 다시 첫 번째 alert 버튼을 클릭합니다.
inputElement = driver.find_element_by_id('simpleAlert')
inputElement.click()
time.sleep(2)

# alert 창의 메시지를 확인하고 싶습니다.
alert = driver.switch_to.alert
message = alert.text
print("Alert shows following message: "+ message )
time.sleep(2)

# 메시지를 확인했으니 창을 닫습니다.
alert = driver.switch_to.alert
alert.accept()
time.sleep(2)



# 두 번째 alert 버튼을 클릭합니다.
inputElement = driver.find_element_by_id('confirmAlert')
inputElement.click()
time.sleep(2)

# alert 창의 '취소'을 클릭합니다.
alert = driver.switch_to.alert
alert.dismiss()
time.sleep(2)

# 다시 두 번째 alert 버튼을 클릭합니다.
inputElement = driver.find_element_by_id('confirmAlert')
inputElement.click()
time.sleep(2)

# alert 창의 '확인'을 클릭합니다.
alert = driver.switch_to.alert
alert.accept()
time.sleep(2)



# 세 번째 alert 버튼을 클릭합니다.
inputElement = driver.find_element_by_id('promptAlert')
inputElement.click()
time.sleep(2)

# alert 창의 '취소'을 클릭합니다.
alert = driver.switch_to.alert
alert.dismiss()
time.sleep(2)

# 다시 세 번째 alert 버튼을 클릭합니다.
inputElement = driver.find_element_by_id('promptAlert')
inputElement.click()
time.sleep(2)

# prompt창에 이름을 씁니다.
alert = driver.switch_to.alert
alert.send_keys('tongchun')
time.sleep(2)

# alert 창의 '확인'을 클릭합니다.
alert = driver.switch_to.alert
alert.accept()
time.sleep(2)


# 실행한 브라우저를 닫습니다.
time.sleep(5)
driver.quit()

참고하시기 바랍니다.