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"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With