selenium有一個專門對付js中的onclick函數告警框的方法html
Methods defined here: __init__(self, driver) Creates a new Alert. :Args: - driver: The WebDriver instance which performs user actions. accept(self) Accepts the alert available. Usage:: Alert(driver).accept() # Confirm a alert dialog. authenticate(self, username, password) Send the username / password to an Authenticated dialog (like with Basic HTTP Auth). Implicitly 'clicks ok' Usage:: driver.switch_to.alert.authenticate('cheese', 'secretGouda') :Args: -username: string to be set in the username section of the dialog -password: string to be set in the password section of the dialog dismiss(self) Dismisses the alert available. send_keys(self, keysToSend) Send Keys to the Alert. :Args: - keysToSend: The text to be sent to Alert. Data descriptors defined here: __dict__ dictionary for instance variables (if defined) __weakref__ list of weak references to the object (if defined) text Gets the text of the Alert.
簡而言之就是先定位到彈出框python
driver.switch_to_alert()
而後再用其方法實現接受,不接受,獲取內容,以及填寫內容web
text accept() dismiss() send_keys()
例子函數
alert.html測試
<html> <head> <title>Alert</title> </head> <body> <input id = "alert" value = "alert" type = "button" onclick = "alert('welcome, please click ok button');"/> <input id = "confirm" value = "confirm" type = "button" onclick = "confirm('do you confirm');"/> <input id = "prompt" value = "prompt" type = "button" onclick = "var name = prompt('please input your name'); document.write(name) "/> </body> </html>
alert.pyui
#coding:utf-8 from selenium import webdriver import time driver = webdriver.Firefox() driver.get("file:\\\C:\\work\\python\\selenium\\Selenium_Auto\\WebDriverAPI\\alert.html") driver.find_element_by_id("alert").click() text_alert = driver.switch_to_alert() print text_alert.text time.sleep(5) text_alert.accept() driver.find_element_by_id("confirm").click() text_confirm = driver.switch_to_alert() print text_confirm.text time.sleep(5) text_confirm.dismiss() driver.find_element_by_id("prompt").click() text_prompt = driver.switch_to_alert() text_prompt.send_keys('terry') print text_prompt.text time.sleep(5) text_prompt.accept() --------------------------------------------------------------------------------------- welcome, please click ok button do you confirm please input your name
參考:code
《Selenium2自動化測試實戰》orm
《selenium python buildings release 2》htm