繁体   English   中英

断言元素不存在 python Selenium

[英]Assert an Element is NOT present python Selenium

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

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

您可以在下面使用:

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

如果找不到与locator匹配的元素,则应该通过断言;如果找到至少1个,则应该通过AssertionError

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

从selenium.webdriver.common.by导入从selenium.webdriver.support.ui导入从selenium.webdriver.support导入WebDriverWait从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

假设您使用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'

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

from selenium.common.exceptions import NoSuchElementException

def test_element_does_not_exist(self):
    with self.assertRaises(NoSuchElementException):
        browser.find_element_by_xpath("locator")

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM