断言元素不存在 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 导入 WebDriverWait从 selenium.webdriver.support 导入expected_conditions作为 EC

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

在这种情况下,我们将AssertionError元素是否在 10 秒内出现在 DOM 中

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

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

  • 使用 assertinvisibility_of_element_located(定位器(,这将断言元素不可见或不存在在 DOM 上。

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

    assert not WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "xpath_Element_Text_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")

最新更新