检查元素是否存在python selenium [英] Check if element exists python selenium

查看:526
本文介绍了检查元素是否存在python selenium的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过

element=driver.find_element_by_partial_link_text("text")

在Python硒中,元素并不总是存在.是否有一条快速的线检查它是否存在,并在不存在时显示NULL或FALSE代替错误消息?

in Python selenium and the element does not always exist. Is there a quick line to check if it exists and get NULL or FALSE in place of the error message when it doesn't exist?

推荐答案

您可以如下实现try/except块,以检查元素是否存在:

You can implement try/except block as below to check whether element present or not:

from selenium.common.exceptions import NoSuchElementException

try:
    element=driver.find_element_by_partial_link_text("text")
except NoSuchElementException:
    print("No element found")

或使用find_elements_...()方法之一进行检查.它应该返回空列表或与传递的选择器匹配的元素列表,但如果没有找到元素,则不会例外:

or check the same with one of find_elements_...() methods. It should return you empty list or list of elements matched by passed selector, but no exception in case no elements found:

elements=driver.find_elements_by_partial_link_text("text")
if not elements:
    print("No element found")  
else:
    element = elements[0]  

这篇关于检查元素是否存在python selenium的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆