selenium自动化之捕获异常
捕获异常
之前学过python的捕获异常,这里学一下selenium的捕获异常,在定位元素的时候,经常会遇到各种异常,可以用try……except 捕获异常,selenium的exceptions模块,获取异常发生的原因
实例一:定位百度输入框,然后输入内容,为了定位失败,将元素属性值“kw”改为“cw”
程序在查找元素时发生中断,不会继续执行send_keys
捕获异常
为了让程序继续执行,可以用try...except...捕获异常。捕获异常后可以打印异常发生的原因
因为是元素无法找到,所以发生异常原因是:NoSuchElementException
从
selenium.common.exceptions 导入 NoSuchElementException类,代码如下
#coding:utf-8
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
driver = webdriver.Firefox()
driver.get("https://www.baidu.com")
try:
element=driver.find_element_by_id("cw")
except NoSuchElementException as msg:
print u"查找元素异常:%s"%msg
else:
element.send_keys(u"selenium")
selenium常见异常
1.NoSuchElementException:没有找到元素
2.NoSuchFrameException:没有找到iframe
3.NoSuchWindowException:没找到窗口句柄handle
4.NoSuchAttributeException:属性错误
5.NoAlertPresentException:没找到alert弹出框
6.lementNotVisibleException:元素不可见
7.ElementNotSelectableException:元素没有被选中
8.TimeoutException:查找元素超时

浙公网安备 33010602011771号