selenium判断指定元素是否存在

  • selenium自身不存在判断元素是否存在的方法;
  • 使用selenium的get_element_by来抓取元素的时候,如果找不到元素必定会弹出异常,没法用is_displayed 等方法来判断是否存在;
    基于以上原因,只能通过抓取和异常捕获自己实现一个判断元素是否存在的功能。下面直接上代码:
# 检查元素是否存在
def check_element_exists(driver, element, condition):
    try:
        if condition == 'class':
            driver.find_element_by_class_name(element)
        elif condition == 'id':
            driver.find_element_by_id(element)
        elif condition == 'xpath':
            driver.find_element_by_xpath(element)
        return True
    except Exception as e:
        return False

你可能感兴趣的:(selenium判断指定元素是否存在)