selenium提供 switch_to_alert方法:捕获弹出对话框(可以定位alert、confirm、prompt对话框)
switch_to_alert() | 定位弹出对话框 |
---|---|
text() | 获取对话框文本值 |
accept() | 相当于点击“确认” |
dismiss() | 相当于点击“取消” |
send_keys() | 输入值(alert和confirm没有输入对话框,所以就不用能用了,只能使用在prompt里) |
测试HTML代码:
示例一:
Alert
示例二:
hello girl
import time
from selenium import webdriver
"""
处理alert弹窗
"""
driver = webdriver.Chrome('F:\PyCharmProject\TestFramework\drivers\chromedriver.exe')
driver.get('file:///C:/Users/Uker/Desktop/seleniumHTML/alert.html')
time.sleep(1)
# 获取alert对话框的按钮,点击按钮,弹出alert对话框
driver.find_element_by_id('alert').click()
time.sleep(1)
# 获取alert对话框
dig_alert = driver.switch_to.alert
time.sleep(1)
# 打印警告对话框内容
print(dig_alert.text)
# alert对话框属于警告对话框,我们这里只能接受弹窗
dig_alert.accept()
time.sleep(1)
driver.quit()
import time
from selenium import webdriver
"""
处理confirm对话框
"""
# 获取confirm对话框的按钮,点击按钮,弹出confirm对话框
driver.find_element_by_id('confirm').click()
time.sleep(1)
# 获取confirm对话框
dig_confirm = driver.switch_to.alert
time.sleep(1)
# 打印对话框的内容
print(dig_confirm.text)
# 点击“确认”按钮
dig_confirm.accept()
# 点击“取消”按钮
# dig_confirm.dismiss()
time.sleep(1)
driver.quit()
import time
from selenium import webdriver
"""
处理prompt对话框
"""
# 获取prompt对话框的按钮,点击按钮,弹出prompt对话框
driver.find_element_by_id('prompt').click()
time.sleep(1)
# 获取prompt对话框
dig_prompt = driver.switch_to.alert
time.sleep(1)
# 打印对话框内容
print(dig_prompt.text)
# 在弹框内输入信息
dig_prompt.send_keys("Loading")
# 点击“确认”按钮,提交输入的内容
dig_prompt.accept()
time.sleep(1)
driver.quit()
原文链接:https://blog.csdn.net/lykio_881210/article/details/80915882