[TOC]
前言
在定位元素的时候,经常会遇到各种异常,为什么会发生这些异常,遇到异常又该如何处理呢?
## 一、发生异常
1. 打开博客首页,定位“新随笔”元素,此元素id="blog\_nav\_newpost"
2. 为了故意让它定位失败,我在元素属性后面加上xx
3. 运行失败后如下图所示,程序在查找元素的这一行发生了中断,不会继续执行click事件了
![Snipaste_2020-09-14_17-36-50.png](http://i.loli.net/2020/09/14/lftJ5ih73Gs4BN9.png)
## 二、捕获异常
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类
![Snipaste_2020-09-14_17-40-44.png](http://i.loli.net/2020/09/14/iImMJHolgaVszxK.png)
## 三、参考代码:
```
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
driver = webdriver.Chrome()
driver.get("https://www.cnblogs.com/zjut-cheng/")
# 定位首页"新随笔"
try:
element = driver.find_element("id", "blog_nav_newpostxx")
except NoSuchElementException as msg:
print("查找元素异常 %s" %msg)
# 点击该元素
else:
element.click()
```
## 四、selenium常见异常
```
1.NoSuchElementException:没有找到元素
2.NoSuchFrameException:没有找到iframe
3.NoSuchWindowException:没找到窗口句柄handle
4.NoSuchAttributeException:属性错误
5.NoAlertPresentException:没找到alert弹出框
6.lementNotVisibleException:元素不可见
7.ElementNotSelectableException:元素没有被选中
8.TimeoutException:查找元素超时
```