alert彈出框涉及到的標籤種類有<alert><confirm><prompt>,常用方法accept(),dismiss(),prompt則要sendkeys(),切換到alert窗口則用alert = driver.switch_to.alert,獲取alert窗口的文字用alert窗口對象.text
暫時沒想到有alert彈出框的網站,一個簡單的小例子
<html>
<head>
<title>Alert</title>
</head>
<body>
<input id = "alert" value = "alert" type = "button" onclick = "alert('歡迎!請按確認繼續!');"/>
<input id = "confirm" value = "confirm" type = "button" onclick = "confirm('確定嗎?');"/>
<input id = "prompt" value = "prompt" type = "button" onclick = "var name = prompt('請輸入你的名字:','請輸入 你的名字'); document.write(name) "/>
</body>
</html>
from selenium import webdriver
from time import sleep
class Test_Alert:
def setup(self):
self.driver = webdriver.Chrome(r"D:\Program Files\chromedriver.exe")
def test_alert1(self):
driver = self.driver
driver.get(r"C:\Users\Lulu\Desktop\alerttest.html")
driver.maximize_window()
# 1.accept()
driver.find_element_by_id("alert").click()
#切換到alert界面,accept相當於點擊確認
print(driver.switch_to.alert.text)
driver.switch_to.alert.accept()
sleep(3)
# 2.dismiss()
driver.find_element_by_id("confirm").click()
driver.switch_to.alert.dismiss()
driver.find_element_by_id("confirm").click()
driver.switch_to.alert.accept()
sleep(2)
# 3. prompt
driver.find_element_by_id("prompt").click()
prompt = driver.switch_to.alert
print("彈出框內容爲:", prompt.text)
prompt.send_keys("趙錢sun'li'zhou'wu'zheng'wang")
prompt.accept()
sleep(3)
def teardown(self):
self.driver.quit()