断言元素不存在python Selenium

时间:2017-02-09 16:33:46

标签: python python-2.7 selenium

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

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

3 个答案:

答案 0 :(得分:4)

您可以在下面使用:

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

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

答案 1 :(得分:1)

假设您在assert中使用py.test进行检查,并且想要验证预期异常的消息:

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'

答案 2 :(得分:0)

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

from selenium.common.exceptions import NoSuchElementException

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