在 selenium webdriver 现在对confirm 和 alert 的处理全面支持,不再需要借助任何第三方工具。
下面的 html 页面上有1个名为 click 的 button, 点击该 button 后就会弹出1个 alert 窗口。
<html>
<head>
<title>Alert</title>
</head>
<body>
<input id = "btn" value = "click" type = "button" onclick = "alert('hello');"/>
</body>
</html>
selenium webdriver 处理 alert 的代码如下:
# coding:utf-8
__author__ = 'zhangzhe'
from selenium import webdriver
import time
import os
#打开IE
driver = webdriver.Chrome()
file_path = 'file:///' + os.path.abspath('alert.html')
driver.get(file_path)
time.sleep(3)
driver.find_element_by_id('btn').click()
'捕获弹出的提示框'
objAlert = driver.switch_to_alert()
#显示提示信息内容
print objAlert.text
#点击确认按钮
objAlert.accept()
上面代码的思路是先点击 id 为 btn 的按钮, 然后 driver.switch_to_alert() 返回了1个 alert
element(暂时如此理解好了)并赋值给变量 objAlert 。这样 objAlert 就代表了 alert,使用 print objAlert.text 语
句可以输出 alert 的内容,这里会打印出’hello’。
objAlert.accept 表示点击确认,当弹出窗口为 confrim 时, objAlert .accept 也表示确认,如果需要取消
的话,那么则可以使用 objAlert .dismiss 方法。