Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert an Element is NOT present python Selenium

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"
like image 736
mike Avatar asked Oct 17 '25 18:10

mike


1 Answers

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

like image 120
Andersson Avatar answered Oct 20 '25 07:10

Andersson