【python】【selenium】Selenium中如何判断元素是否存在?

Selenium中没有提供原生的方法判断元素是否存在,一般我们可以通过定位元素+异常捕获的方式判断。Python示例代码如下:

from selenium.common.exceptions import NoSuchElementException

# 判断元素是否存在
def isElementPresent(self, by, value):
    try:
        element =self.driver.find_element(by=by, value=value)
    except NoSuchElementException as e:
# 发生了NoSuchElementException异常,说明页面中未找到该元素,返回False
        return  False
    else:
# 没有发生异常,表示在页面中找到了该元素,返回True
        return  True 

 

posted @ 2022-03-28 16:05  放手Forrest  阅读(4553)  评论(0)    收藏  举报