检查元素是否存在[重复]

问题描述 投票:0回答:2

这个问题在这里已有答案:

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 ='Status'] “}

python python-3.x selenium selenium-webdriver webdriver
2个回答
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()

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()
© www.soinside.com 2019 - 2024. All rights reserved.