selenium有一个专门对付js中的onclick函数告警框的方法
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.
简而言之就是先定位到弹出框
driver.switch_to_alert()
然后再用其方法实现接受,不接受,获取内容,以及填写内容
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.py
#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
参考:
《Selenium2自动化测试实战》
《selenium python buildings release 2》