断言元素不存在python Selenium

2024-05-23 16:50:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: 方法text元素bydriverseleniumnotassert
3条回答

您可以使用以下选项:

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

如果找不到与您的locator匹配的元素,或者至少找到1个AssertionError匹配的元素,则应该传递断言

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

从selenium.webdriver.common.by导入 从selenium.webdriver.support.ui导入WebDriverWait 从selenium.webdriver.support将预期条件导入为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

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

from selenium.common.exceptions import NoSuchElementException

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

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

相关问题 更多 >