Python自动化测试系列[v1.0.0][处理弹窗]

我们常见的弹窗一般分为3个样式,分别成为alert/prompt/confirm,同样的要定位弹窗控件中的元素或者操作控件都必须先切换进控件内

被测页面

<html>  
	<head>  
		<title>For Test Alert</title>  
	</head>  
	<body>  
		<input id = "alert" value = "alert" type = "button" onclick = "alert('您点击了alert按钮');"/>  
		<input id = "confirm" value = "confirm" type = "button" onclick = "confirm('您点击了confirm按钮');"/>  
		<input id = "prompt" value = "prompt" type = "button" onclick = "var name = prompt('您点击了prompt按钮:','Prompt'); document.write(name) "/>    
	</body>   
</html>  

方法封装

def switch_to_alert(self):
    """
    切换进alert控件
    :return:
    """
    pop_dailog = self.driver.switch_to.alert
    return pop_dailog

方法调用

def test_switch_to_alert(self):
    chrome_driver = webdriver.Chrome()
    # 浏览器打开我们刚才新建的html文件
    chrome_driver.get("file:///C:/Users/davieyang/Desktop/test_alert.html")
    time.sleep(3)
    #  点击alert按钮
    chrome_driver.find_element_by_id("alert").click()
    time.sleep(3)
    #  调用我们封装好的方法
    al = Browser_Controller(chrome_driver).switch_to_alert()
    print(al.text)  #  打印弹窗中的文本
    # 相当于点击弹窗中的确定按钮,但实际并不是点击只是弹窗对象提供的方法,效果一样
    al.accept()
def test_switch_to_confirm(self):
    chrome_driver = webdriver.Chrome()
    # 浏览器打开我们刚才新建的html文件
    chrome_driver.get("file:///C:/Users/davieyang/Desktop/test_alert.html")
    time.sleep(3)
    #  点击alert按钮
    chrome_driver.find_element_by_id("confirm").click()
    time.sleep(3)
    #  调用我们封装好的方法
    al = Browser_Controller(chrome_driver).switch_to_alert()
    print(al.text)  #  打印弹窗中的文本
    # 相当于点击弹窗中的取消按钮,但实际并不是点击只是弹窗对象提供的方法,效果一样
    al.dismiss()
def test_switch_to_prompt(self):
    chrome_driver = webdriver.Chrome()
    # 浏览器打开我们刚才新建的html文件
    chrome_driver.get("file:///C:/Users/davieyang/Desktop/test_alert.html")
    time.sleep(3)
    #  点击alert按钮
    chrome_driver.find_element_by_id("prompt").click()
    time.sleep(3)
    #  调用我们封装好的方法
    al = Browser_Controller(chrome_driver).switch_to_alert()
    print(al.text)  #  打印弹窗中的文本
    # 相当于点击弹窗中的确定按钮,但实际并不是点击只是弹窗对象提供的方法,效果一样
    al.accept()

发布了231 篇原创文章 · 获赞 188 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/dawei_yang000000/article/details/105648600