Python检测Linux网络异常,38- 捕获异常(NoSuchElementException)

[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:查找元素超时

```

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值