‘‘‘
Created on November 22, 2014
@author: Songjin
‘‘‘
from Selenium import webdriver
Import Time
from Selenium.webdriver.support.ui import webdriverwait
from Selenium.webdriver.support import expected_conditions as EC
from Selenium.webdriver import Firefox
from Selenium.webdriver.common.keys import keys
#Firefoxdriverpath=os.path.abspath ("/applications/firefox.app/contents/macos/firefoxdriver")
#os. environ["Webdriver.firefox.driver"]=firefoxdriverpath
#driver =webdriver. Firefox (firefoxdriverpath)
#driver =webdriver. Firefox ()
Driver=webdriver. Firefox ()
driver.get ("http://www.baidu.com")
#点击打开搜索设置
Driver.find_element_by_css_selector ("#u1 > A[name= ' Tj_settingicon ']"). Click ()
Driver.find_element_by_css_selector ("A.setpref"). Click ()
#点击保存设置
Driver.implicitly_wait (ten)
#driver. Find_element_by_css_selector ("div#gxszButton a.prefpanelgo[href= ' # ']"). Click ()
Driver.find_element_by_link_text ("Save Settings"). Click ()
Time.sleep (2)
#driver. Find_element_by_css_selector ("div#gxszButton a.prefpanelgo[href= ' # ']")
#获取网页上的警告信息
#alert =driver.switch_to_alert (). Text ()
if Ec.alert_is_present:
Print("Alert exists")
Alert=driver.switch_to_alert ()
Print (Alert.text)
Alert.accept ()
Print("Alert accepted")
else:
Print("NO alert exists")
‘‘‘
Try
Webdriverwait (driver,10). Until (Ec.alert_is_present (),
' Timed out waiting for PA creation ' +
' Confirmation popup to appear. ')
Print ("0")
Alert=driver.switch_to_alert (). Text ()
Print ("1")
Text=alert.text ()
Print (text)
Except TimeoutException:
Print ("no alert")
#接收警告信息
#alert. Accept ()
#print ("3")
#得到文本信息并打印
#alert =driver.switch_to_alert ()
#print ("5")
#取消对话框 (if any)
#alert =driver.switch_to_alert ()
#alert. Dismiss ()
#输入值 (if any)
#alert =driver.switch_to_alert ()
#alert. Send_keys ("xxx")
‘‘‘
Driver.quit ()
If Switch_to_alert does not work, the most important problem is that more than 1 browsers are turned on, causing alert to crawl. And in the use of Switch_to_alert time will be longer, need to wait a while to complete the work of accept and so on.
The reason is that because multiple browsers are turned on to be unable to locate exactly which browser, such as a browser that has two Firefox at the same time, Webdriver cannot locate the browser to be tested and will not be able to get to the alert window on the test browser.
Python+selenium use Switch_to_alert Strange exception