我們常見的彈窗一般分爲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()