当前位置: 首页> 房产> 市场 > 31-捕获异常(NoSuchElementException)

31-捕获异常(NoSuchElementException)

时间:2025/7/12 20:53:28来源:https://blog.csdn.net/zhangzhan0813/article/details/139578009 浏览次数:0次

        在定位元素的时候,经常会遇到各种异常,遇到异常又该如何处理呢?本篇通过学习selenium的exceptions模块,了解异常发生的原因。

一、发生异常

        打开百度搜索首页,定位搜索框,此元素id="kw"。为了故意让它定位失败,我在元素属性后面加上xx,运行失败后如下图所示,程序在定位搜索框的这一行发生了中断,不会继续执行后续代码了。

from selenium import webdriver
import timedriver = webdriver.Chrome()
driver.get('https://www.baidu.com')
element = driver.find_element('id', 'kwxx')
element.send_keys('python')
time.sleep(5)

二、捕获异常

        为了让程序继续执行,我们可以用 try...except... 捕获异常。捕获异常后可以打印出异常原因,这样以便于分析异常原因。从如下异常内容可以看出,发生异常原因是:NoSuchElementException。selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="kwxx"]"}

        从 selenium.common.exceptions 导入 NoSuchElementException 类。

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementExceptiondriver = webdriver.Chrome()
driver.get('https://www.baidu.com')
try:element = driver.find_element('id', 'kwxx')
except NoSuchElementException as e:print("报错:{}".format(e))
else:element.send_keys('python')

三、selenium常见异常

NoSuchElementException:没有找到元素
NoSuchFrameException:没有找到iframe
NoSuchWindowException:没找到窗口句柄handle
NoSuchAttributeException:属性错误
NoAlertPresentException:没找到alert弹出框
ElementNotVisibleException:元素不可见
ElementNotSelectableException:元素没有被选中
TimeoutException:查找元素超时
关键字:31-捕获异常(NoSuchElementException)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: