Reputation: 117
I am using selenium python and looking for a way to assert that an element is not present, something like:
assert not driver.find_element_by_xpath("locator").text== "Element Text"
Upvotes: 4
Views: 18485
Reputation: 193308
To assert that an element is not present you can use either of the following approaches:
Using assert
and invisibility_of_element_located(locator) which will assert that an element is either invisible or not present on the DOM.
assert WebDriverWait(driver, 20).until(EC.invisibility_of_element_located((By.XPATH, "xpath_Element_Text_element")))
Using assert not
and visibility_of_element_located(locator) which will assert that an element is not present on the DOM of a page and not visible.
assert not WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "xpath_Element_Text_element")))
Upvotes: 3
Reputation: 1655
If you are trying to check that an element does not exist, the easiest way to do that is using a with statement.
from selenium.common.exceptions import NoSuchElementException
def test_element_does_not_exist(self):
with self.assertRaises(NoSuchElementException):
browser.find_element_by_xpath("locator")
Upvotes: 3
Reputation: 52685
You can use below:
assert not len(driver.find_elements_by_xpath("locator"))
This should pass assertion if none of elements that match your locator
were found or AssertionError
if at least 1 found
Note, that if element is generated dynamically by some JavaScript
it could appear in DOM
after assertion executed. In this case you might implement ExplicitWait :
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import 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
In this case we'll get AssertionError
if element appeared in DOM within 10 seconds
Upvotes: 5
Reputation: 2759
assuming you are using py.test for your check in assert
and you want to verify the message of an expected exception:
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'
Upvotes: 4