【selenium学习 -10】alter,prompt,confirm弹窗的处理

本文主要介绍selenium对alter,prompt,confirm弹窗的处理

1.alter弹窗

HTML代码

<html>
<button id="clickme" type="button" onclick="display_alter()">Click Me</button>

<script>
    function display_alter() {
        alert("我是弹窗!!!!!")
    }
</script>

</html>

Python代码:

from selenium import webdriver
import time

if __name__ == '__main__':
    driver = webdriver.Chrome()
    driver.maximize_window()
    driver.get("file:///xxxxx/Selenium/HTMLTest/alter-test.html")
    driver.find_element_by_id("clickme").click()
    time.sleep(1)
    #获取对话框
    alter_window=driver.switch_to.alert
    # 打印对话框内容
    print(alter_window.text)
    time.sleep(1)
    #点击确认
    alter_window.accept()

总结:先通过switch_to.alert切换到对话框上,alter对话框只能点击“确认”,所以这里只涉及到两个方法

text方法获取文本信息,accept()方法点击确认按钮

2.confirm弹窗

HTML代码

<html>
<body>
    <button id="clickme" onclick="myFunction()">点我</button>
    <p id="demo"></p>
    <script>
        function myFunction() {
            var x;
            var r = confirm("按下按钮!");
            if (r == true) {
                x = "你按下了"确定"按钮!";
            } else {
                x = "你按下了"取消"按钮!";
            }
            document.getElementById("demo").innerHTML = x;
        }
    </script>

</body>

</html>

Python代码:

from selenium import webdriver
import time

if __name__ == '__main__':
    driver = webdriver.Chrome()
    driver.maximize_window()
    driver.get("file:///xxxx/Selenium/HTMLTest/confirm-test.html")
    driver.find_element_by_id("clickme").click()
    time.sleep(1)
    #获取对话框
    dialog_box=driver.switch_to.alert
    # 打印对话框内容
    print(dialog_box.text)
    time.sleep(1)
    #点击确认
    dialog_box.accept()


    #重头再点击一遍“取消”按钮
    time.sleep(5)
    driver.find_element_by_id("clickme").click()
    dialog_box = driver.switch_to.alert
    dialog_box.dismiss()

总结:先通过switch_to.alert切换到对话框上,confirm对话框可以点击确认和取消

accept()点击确认

dismiss()点击取消

3.prompt弹窗

HTML代码:

<html>
<button id="clickme" onclick="myFunction()">点我</button>
<p id="demo"></p>

<script>
    function myFunction() {
        var person = prompt("请输入你的名字");
        if (person != null && person != "") {
            document.getElementById("demo").innerHTML = person;
        }
    }
</script>

</body>
</html>

 Python代码:

from selenium import webdriver
import time

if __name__ == '__main__':
    driver = webdriver.Chrome()
    driver.maximize_window()
    driver.get("file:///D:xxxx/Selenium/HTMLTest/prompt-test.html")
    driver.find_element_by_id("clickme").click()
    time.sleep(1)
    #获取对话框
    alter_window=driver.switch_to.alert
    # 打印对话框内容
    print(alter_window.text)
    # 在对话框内输入文字
    alter_window.send_keys("我的名字是莱亚斯")
    alter_window.accept()

总结:先通过switch_to.alert切换到对话框上

text方法获取文本信息

accept()点击确认

dismiss()点击取消

send_keys()方法输入内容

综上所述:三种弹窗的处理方式大同小异,都是先switch_to.alert切换到弹出框上,然后通过accept()方法和dismiss()方法来进行操作

原文地址:https://www.cnblogs.com/ronyjay/p/12916982.html