码迷,mamicode.com
首页 > 编程语言 > 详细

python+selenium 使用switch_to_alert 出现的怪异常

时间:2014-11-23 07:09:08      阅读:300      评论:0      收藏:0      [点我收藏+]

标签:style   http   io   ar   color   os   使用   sp   for   

‘‘‘

Created on 2014年11月22日


@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(10)

#driver.find_element_by_css_selector("div#gxszButton a.prefpanelgo[href=‘#‘]").click()

driver.find_element_by_link_text("保存设置").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")

#取消对话框(如果有的话)

#alert=driver.switch_to_alert()

#alert.dismiss()


#输入值(如果有的话)

#alert=driver.switch_to_alert()

#alert.send_keys("xxx")

‘‘‘

driver.quit()

如果switch_to_alert不工作,最重要的问题就是,有1个以上的浏览器开启,导致alert抓取不到。并且在使用switch_to_alert的时候时间会比较长一些,需要等待一会儿才能完成accept等的工作。

原因是因为多个浏览器开启导致无法准确定位到哪个浏览器上,例如同时开启了两个firefox的浏览器,webdriver就无法定位到要测试的那个浏览器上,也就无法正常的获取到测试的那台浏览器上的alert窗口。

python+selenium 使用switch_to_alert 出现的怪异常

标签:style   http   io   ar   color   os   使用   sp   for   

原文地址:http://my.oschina.net/u/855532/blog/347709

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!