最近学习Selenium2,关于警告框处理这里,碰到“保存设置”按钮点击,始终报错ElementNotVisibleException,书中的例子,仔细核对,还是有问题,查了很多资料,终于解决。
'''
Author: lxt
Date: 2017/03/29
Method:
* text:返回 alert/confirm/prompt 中的文字信息。
* accept():接受现有警告框。
* dismiss():解散现有警告框。
* send_keys(keysToSend): 发送文本至警告框。 keysToSend:将文本发送至警告框。
'''
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import ElementNotVisibleException
from selenium.common.exceptions import NoSuchElementException
from time import ctime
driver =webdriver.Chrome()
'''
implicitly_wait()超时则抛出NoSuchElementException
'''
driver.implicitly_wait(10)
driver.get("http://www.baidu.com")
'''
#鼠标悬停至“设置”链接 作用同下面by_link_text("设置").click()
link =driver.find_element_by_link_text("设置")
ActionChains(driver).move_to_element(link).perform()
'''
print(ctime())
driver.find_element_by_link_text("设置").click()
#打开搜索设置
driver.find_element_by_class_name("setpref").click()
'''点击保存设置前休眠2s'''
#time.sleep(2)
#保存设置
try:
print(ctime())
driver.find_element_by_class_name("prefpanelgo").click()
time.sleep(2)
#接受警告框
driver.switch_to_alert().accept()
except ElementNotVisibleException as e:
print("ElementNotVisibleException---")
print(e)
except NoSuchElementException as e:
print("NoSuchElementException---")
print(e)
finally:
print(ctime())
driver.quit()
提示找不到element时考虑一下1.框架跳转问题 2.加载还没完成(这次就是这个原因,sleep2秒)
另外仍有几点不明白就是
1.关于driver.implicitly_wait(10),从打印的结果来看,时间并未休眠10S
2.如果加上driver.implicitly_wait(10),“保存设置”点击之前,未休眠2s时,捕捉到“ElementNotVisibleException”异常
3.如果注释掉driver.implicitly_wait(10),“保存设置”点击之前,未休眠2s时,捕捉到“NoSuchElementException”异常
所以并未像书中提到的隐式等待implicitly_wait(),能抛出NoSuchElementException 异常,并且未达到指定休眠时间。
后面继续研究。