3.11 练习题2:捕获异常
3.11 练习题2:捕获异常
前言
在定位元素的时候,经常会遇到各种异常,为什么会发生这些异常,遇到异常又该如何处理呢?
本篇通过学习selenium的exceptions模块,了解异常发生的原因。
一、发生异常
1.打开博客首页,定位“新随笔”元素,此元素id="blog_nav_newpost"
2.为了故意让它定位失败,我在元素属性后面加上xx
3.运行失败后如下图所示,程序在查找元素的这一行发生了中断,不会继续执行click事件了
二、捕获异常
1.为了让程序继续执行,我们可以用try...except...捕获异常。捕获异常后可以打印出异常原因,这样以便于分析异常原因。
2.从如下异常内容可以看出,发生异常原因是:NoSuchElementException
selenium.common.exceptions.NoSuchElementException:
Message: Unable to locate element:
{"method":"id","selector":"blog_nav_newpostxx"}
3.从selenium.common.exceptions 导入 NoSuchElementException类。
三、参考代码:
# coding:utf-8
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
driver = webdriver.Firefox()
driver.get("http://www.cnblogs.com/yoyoketang/")
# 定位首页"新随笔"
try:
element = driver.find_element("id", "blog_nav_newpostxx")
except NoSuchElementException as msg:
print u"查找元素异常%s"%msg
# 点击该元素
else:
element.click()
四、selenium常见异常
1.NoSuchElementException:没有找到元素
2.NoSuchFrameException:没有找到iframe
3.NoSuchWindowException:没找到窗口句柄handle
4.NoSuchAttributeException:属性错误
5.NoAlertPresentException:没找到alert弹出框
6.ElmentNotVisibleException:元素不可见
7.ElementNotSelectableException:元素没有被选中
8.TimeoutException:查找元素超时
备注:其它异常与源码在Lib目录下:selenium/common/exceptions有兴趣的可以看看。