python - Selenium (如果在屏幕上定位无法找到元素)

标签 python selenium if-statement error-handling

我将使这个问题简单化:
我有一个if语句:

if self.driver.find_element_by_xpath('//*[contains(@id, "mission_countdown")]'):

我得到这个错误:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[contains(@id, "mission_countdown")]"}

为什么我得到这个?我的意思是它的if语句,如果它在屏幕上

感谢您的帮助

最佳答案

find_element_by_xpath可以返回

  • WebElement(如果找到)
  • NoSuchElementException(如果未找到)

  • 如果您正在搜索可评估为boolean以便在if/else块中使用的输出,请尝试find_elements:
    if self.driver.find_elements_by_xpath('//*[contains(@id, "mission_countdown")]'):
        print('At least one element was found')
    else:
        print('No elements found')
    

    关于python - Selenium (如果在屏幕上定位无法找到元素),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54933394/

    相关文章:

    python - 需要检查容器是否在运行

    python - 从 Python 内部设置 LD_LIBRARY_PATH

    angularjs - 当我有 Cucumber 和 Selenium 时,为什么还需要 Protractor?

    python - Selenium python根据给定的参数从表行中选择表数据

    java - 同一个数组中不就是多个相同的字符串名吗?

    javascript - if 语句是否创建局部作用域?

    python - 使用 arcpy : strange behaviour of SearchCursor 在列表中加载要素类

    python - 写下 Bokeh 图所选数据不起作用

    java - 如果元素类型为 <object></object>,如何使用 Selenium(对于 Java)定位输入文本框

    python - 使用列表中的任何值进行逻辑检查?