检查元素是否存在

时间:2018-08-31 12:09:38

标签: python python-3.x selenium selenium-webdriver webdriver

def status_button_check():
    if(driver.find_element_by_xpath("//div[@role='button' and @title='Status']")):
        s_b_c_status = "True"
    else:
        s_b_c_status = "False"
    print(s_b_c_status)
status_button_check()

试图检查元素是否存在,但这给了我以下错误:

  

selenium.common.exceptions.NoSuchElementException:消息:没有这样的消息   元素:无法找到元素:   “ method”:“ xpath”,“ selector”:“ // div [@ role ='button'和   @ title ='状态']“}

2 个答案:

答案 0 :(得分:2)

错误消息...

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: "method":"xpath","selector":"//div[@role='button' and @title='Status']"}

...表示您使用的 XPath 无法在HTML DOM中找到任何元素。

如果要验证所需元素的存在,则需要按以下步骤引发try-catch{}块:

def status_button_check():
    try:
        if(driver.find_element_by_xpath("//div[@role='button' and @title='Status']")):
            s_b_c_status = "True"
    except NoSuchElementException:
            s_b_c_status = "False"
    print(s_b_c_status)
status_button_check()

答案 1 :(得分:0)

编写此代码

def status_button_check():
    if(driver.find_elements_by_xpath("//div[@role='button' and @title='Status']")>0):
        s_b_c_status = "True"
    else:
        s_b_c_status = "False"
    print(s_b_c_status)
status_button_check()