1.写一个html页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="javascript:alert('提示框')" id="alert">Alert</a><br>
<a href="javascript:confirm('真的要删除数据吗?')" id="confirm">Confirm</a><br>
<a href="javascript:var age=prompt('请输入年龄');document.write(age)" id="prompt">prompt</a><br>
</body>
</html>
处理弹框代码如下:
from selenium import webdriver
from time import sleep
import os
class testcase():
def __init__(self):
self.driver=webdriver.Chrome()
# 获取绝对路径地址
patch = os.path.dirname(os.path.abspath(__file__))
print(patch)
# 拼接地址
file_patch = 'file:///' + patch + '/test_alert.html'
print(file_patch)
self.driver.get(file_patch)
def test_alert(self):
"""点击alert弹框的处理方法"""
self.driver.find_element_by_id('alert').click()
#切换到alert
alert=self.driver.switch_to.alert
print(alert.text)
sleep(3)
alert.accept()
def test_confirm(self):
"""处理confirm方法"""
self.driver.find_element_by_id('confirm').click()
#切换到confirm
confirm=self.driver.switch_to.alert
print(confirm.text)
sleep(1)
#点击确定按钮
#confirm.accept()
#点击取消按钮
confirm.dismiss()
def test_prompt(self):
#处理prompt方法
self.driver.find_element_by_id('prompt').click()
sleep(2)
#切换弹窗
prompt=self.driver.switch_to.alert
print(prompt.text)
sleep(2)
prompt.accept()
sleep(5)
if __name__ == '__main__':
case=testcase()
#case.test_alert()
#case.test_confirm()
case.test_prompt()
case.driver.quit()