【问题标题】:Selenium Python - Handling No such element exceptionSelenium Python - 处理没有这样的元素异常
【发布时间】:2016-10-27 14:52:44
【问题描述】:

我正在使用 Python 在 Selenium 中编写自动化测试。一种元素可能存在也可能不存在。我正在尝试使用以下代码处理它,它在元素存在时起作用。但是当元素不存在时脚本失败,如果元素不存在,我想继续下一条语句。

try:
       elem = driver.find_element_by_xpath(".//*[@id='SORM_TB_ACTION0']")
       elem.click()
except nosuchelementexception:
       pass

错误 -

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element:{"method":"xpath","selector":".//*[@id='SORM_TB_ACTION0']"}

【问题讨论】:

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


    【解决方案1】:

    你没有导入异常吗?

    from selenium.common.exceptions import NoSuchElementException
    
    try:
        elem = driver.find_element_by_xpath(".//*[@id='SORM_TB_ACTION0']")
        elem.click()
    except NoSuchElementException:  #spelling error making this code not work as expected
        pass
    

    【讨论】:

      【解决方案2】:

      您可以查看该元素是否存在,如果存在则单击它。不需要例外。注意.find_elements_* 中的复数“s”。

      elem = driver.find_elements_by_xpath(".//*[@id='SORM_TB_ACTION0']")
      if len(elem) > 0
          elem[0].click()
      

      【讨论】:

      • 性能上不是差很多吗?我相信通过 id 而不是 xpath 查找元素要容易得多。
      • @SergeRogatch 同意 100% 但这就是 OP 在他们的代码中的内容,所以我复制了它。这也是 4 年前的事了,我想从那以后我学到了很多东西,现在除了“只是回答问题”之外,我更倾向于提出像你这样的观点。
      【解决方案3】:

      你这样做的方式很好..你只是想捕捉错误的异常。它被命名为NoSuchElementException 而不是nosuchelementexception

      【讨论】:

        【解决方案4】:

        处理 Selenium NoSuchExpressionException

        from selenium.common.exceptions import NoSuchElementException
        try:
           candidate_Name = j.find_element_by_xpath('.//span[@aria-hidden="true"]').text
        except NoSuchElementException:
               try:
                  candidate_Name = j.find_element_by_xpath('.//a[@class="app-aware link"]').text
               except NoSuchElementException:
                      candidate_Name = "NAN"
                      pass
        

        【讨论】:

          【解决方案5】:

          为什么不简化和使用这样的逻辑呢?不需要例外。

          if elem.is_displayed():
              elem.click()
          

          【讨论】:

          • 如果找不到该元素,则会抛出此错误。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-03-21
          • 2021-07-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多