Our common pop-up windows are generally divided into 3 styles, which are alert / prompt / confirm. Similarly, to locate the elements or operation controls in the pop-up window control, you must first switch into the control
Tested page
<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>
Method encapsulation
def switch_to_alert(self):
"""
切换进alert控件
:return:
"""
pop_dailog = self.driver.switch_to.alert
return pop_dailog
Method call
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()