前戲
我們常見的彈框有三種,一種是alert彈框,一種是prompt彈框,還有一種是confirm彈框那他們有什么不同呢?不同點就是他們長的不一樣,alert彈框有一段文字和一個確定按鈕,如下
在來看一下prompt長什么樣
confirm長這樣
看完上面的三個框,大家應該能區分出什么框是哪種類型的了吧。。。
處理alert彈框
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="button" id="button" onclick="alert('這是一個alert彈出框')" value="單擊此按鈕"> </body> </html>
from selenium import webdriver import time,unittest from selenium.common.exceptions import NoAlertPresentException class Test_Alert(unittest.TestCase): def test_HandleAlert(self): url = r'E:\JSSCRIPT.html' self.driver = webdriver.Chrome() self.driver.get(url) button = self.driver.find_element_by_id('button') button.click() try: # 使用driver.switch_to.alert()方法獲取alert對象 alert = self.driver.switch_to_alert() time.sleep(2) # 斷言彈出框里的內容 self.assertEqual(alert.text, '這是一個alert彈出框') # 調用alert對象的accept()方法,模擬鼠標單擊alert彈窗上的“確定”按鈕 alert.accept() except NoAlertPresentException as e: print(e) test1 = Test_Alert() test1.test_HandleAlert()
處理prompt彈框
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="button" id="button" onclick="prompt('這是一個prompt彈出框')" value="單擊此按鈕"> </body> </html>
from selenium import webdriver import time,unittest from selenium.common.exceptions import NoAlertPresentException class Test_prompt(unittest.TestCase): def test_HandleAlert(self): url = r'E:\JSSCRIPT.html' self.driver = webdriver.Chrome() self.driver.get(url) button = self.driver.find_element_by_id('button') button.click() try: # 使用driver.switch_to.alert()方法獲取alert對象 alert = self.driver.switch_to_alert() time.sleep(2) # 斷言彈出框里的內容 self.assertEqual(alert.text, '這是一個prompt彈出框') # 往框里輸入值 alert.send_keys('我要搞自動化。。。') # 沒輸入但是也沒報錯 time.sleep(4) alert.accept() # 模擬點擊確定按鈕 except NoAlertPresentException as e: print(e) test1 = Test_prompt() test1.test_HandleAlert()
處理confirm彈框
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="button" id="button" onclick="prompt('這是一個confirm彈出框')" value="單擊此按鈕"> </body> </html>
from selenium import webdriver import time,unittest from selenium.common.exceptions import NoAlertPresentException class Test_confirm(unittest.TestCase): def test_HandleAlert(self): url = r'E:\JSSCRIPT.html' self.driver = webdriver.Chrome() self.driver.get(url) button = self.driver.find_element_by_id('button') button.click() try: # 使用driver.switch_to.alert()方法獲取alert對象 alert = self.driver.switch_to.alert time.sleep(2) # 斷言彈出框里的內容 self.assertEqual(alert.text, '這是一個confirm彈出框') # 往框里輸入值 alert.send_keys('我要搞自動化。。。') # 沒輸入但是也沒報錯 time.sleep(4) alert.accept() # 模擬點擊確定按鈕 alert.dismiss() # 點擊取消按鈕 和上面的取其一 except NoAlertPresentException as e: print(e) test1 = Test_confirm() test1.test_HandleAlert()