webdriver 中处理 JavaScript 所生成的 alert、confirm 以及 prompt 是很简单的。具体思路是使用 switch_to.alert()方法定位到 alert/confirm/prompt。然后使用 text/accept/dismiss/send_keys 按需进行操做。
先来看看各个弹窗的样式:
alert弹窗:
confirm弹窗
prompt弹窗
再来看看Alert具体操作:
.text 返回alert/confirm/prompt中的文字信息
.accpet 点击确认按钮
.dismiss 点击取消按钮
.send_keys 输入值→主要针对prompt弹窗使用
.authenticate 验证,针对需要身份验证的alert
实例代码如下:
alert操作
# coding = utf-8
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.common.alert import Alert
driver = webdriver.Chrome()
print("---------alert操作实例-------")
url1 = "http://sahitest.com/demo/alertTest.htm"
driver.get(url=url1)
driver.maximize_window()
#定位到alert按钮
driver.find_element(By.XPATH,"//input[@id = 'b1']").click()
#通过switch_to_alert切换到alert
a1 =driver.switch_to.alert
#点击alert的确定按钮
a1.accept()
time.sleep(2)
#打印alert信息
print(a1.text)
confirm操作:
# coding = utf-8
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.common.alert import Alert
driver = webdriver.Chrome()
print("---------confirm-------")
url2 = "http://sahitest.com/demo/confirmTest.htm"
# driver= webdriver.Firefox()
driver.get(url=url2)
driver.maximize_window()
#定位到check for prompt按钮
driver.find_element(By.XPATH,"//input[@name = 'b1']").click()
#直接实例化alert对象
a2 = Alert(driver)
time.sleep(2)
print(a2.text)
# a2.accept()
a2.dismiss()
driver.quit()
prompt操作
# coding = utf-8
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.common.alert import Alert
driver = webdriver.Chrome()
print("---------prompt-------")
url3 = "http://sahitest.com/demo/promptTest.htm"
driver.maximize_window()
driver.get(url=url3)
driver.find_element(By.XPATH,"//input[@name = 'b1']").click()
time.sleep(2)
#通过switch_to.alert切换到alert
a3 = driver.switch_to.alert
print(a3.text)
#在prompt型alert中输入字符
a3.send_keys("selenium")
time.sleep(2)
a3.accept()
#页面文本框输出的信息
val = driver.find_element(By.XPATH,"//input[@name = 't1']").get_attribute('value')
time.sleep(3)
print(val)
driver.quit()
以上就是alert/confirm/prompt弹窗的处理方法。