【问题标题】:Assert an Element is NOT present python Selenium断言元素不存在 python Selenium
【发布时间】:2017-06-27 18:41:23
【问题描述】:

我正在使用 selenium python 并寻找一种方法来断言元素不存在,例如:

assert not driver.find_element_by_xpath("locator").text== "Element Text"

【问题讨论】:

  • 那行代码有什么问题?
  • @BlackBear 好吧,根据超时时间,这不会需要很长时间吗?
  • 它失败了,说:无法定位元素

标签: python python-2.7 selenium


【解决方案1】:

要断言元素存在,您可以使用以下任一方法:

  • 使用 assertinvisibility_of_element_located(locator) 将断言元素在 DOM 上不可见或不存在。

    assert WebDriverWait(driver, 20).until(EC.invisibility_of_element_located((By.XPATH, "xpath_Element_Text_element")))
    
  • 使用 assert notvisibility_of_element_located(locator) 将断言元素不存在于页面的 DOM 中且不可见。

    assert not WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "xpath_Element_Text_element")))
    

【讨论】:

    【解决方案2】:

    如果您要检查某个元素是否不存在,最简单的方法是使用 with 语句。

    from selenium.common.exceptions import NoSuchElementException
    
    def test_element_does_not_exist(self):
        with self.assertRaises(NoSuchElementException):
            browser.find_element_by_xpath("locator")
    

    【讨论】:

      【解决方案3】:

      你可以在下面使用:

      assert not len(driver.find_elements_by_xpath("locator"))
      

      如果没有找到与您的 locator 匹配的元素,则这应该通过断言,或者如果至少找到 1 个匹配 AssertionError,则应该通过断言

      注意,如果元素是由某些JavaScript 动态生成的,它可能会出现在DOM 断言执行之后。在这种情况下,您可以实现 ExplicitWait

      从 selenium.webdriver.common.by 导入 从 selenium.webdriver.support.ui 导入 WebDriverWait from selenium.webdriver.support import expected_conditions as EC

      try:
          WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "locator")))
          not_found = False
      except:
          not_found = True
      
      assert not_found
      

      在这种情况下,如果元素在 10 秒内出现在 DOM 中,我们将得到 AssertionError

      【讨论】:

        【解决方案4】:

        假设您使用 py.test 签入 assert 并且您想要验证预期异常的消息:

        import pytest
        
        def test_foo():
            with pytest.raises(Exception) as excinfo:
                x = driver.find_element_by_xpath("locator").text
            assert excinfo.value.message == 'Unable to locate element'
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-10-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-04-21
          相关资源
          最近更新 更多