selenium的弹框处理

页面上的弹框主要有三种:

  • alert:用来提示
  • confirm:用来确认
  • prompt:输入内容
    处理弹框的主要方法和属性如下所示:
    在这里插入图片描述
    使用的html页面如下所示:与下面代码属于同一目录
<!DOCTYPE html>
<html>
<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:prompt('请输入年纪')" id="prompt">prompt</a><br>
</body>

</html>

测试三种弹出框的代码如下所示:

from selenium import webdriver
from time import sleep
import os
class TestCase(object):
    def __init__(self):
        self.driver = webdriver.Chrome()
        path = os.path.dirname(os.path.abspath(__file__))
        file_path = 'file:///' + path + '/test_alert.html'
        self.driver.get(file_path)

    def test_alert(self):
        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):
        self.driver.find_element_by_id('confirm').click()
        confirm = self.driver.switch_to.alert
        print(confirm.text)
        # confirm.accept()
        #
        sleep(3)
        confirm.dismiss()

    def test_prompt(self):
        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()

版权声明:本文为dingding_ting原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。