-1

I am currently trying to verify that the element is not present in the DOM: I have written this function:

element = self.driver.find_element_by_xpath(xpath)     
if element.is_displayed():         
    raise Exception("Element should not be found")     
else:
    pass

I am receiving message:

Unable to locate element
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Vidya
  • 19
  • 1

3 Answers3

1

Please use find_elements_by_xpath.

if len(self.driver.find_elements_by_xpath(xpath)) > 0:         
    raise Exception("Element should not be found")     
else:
    pass
Canopus
  • 565
  • 3
  • 17
1

is_displayed() only checks whether the element is shown to the user (visible) - not the existence.

Also find_element_by_xpath() raises an NoSuchElementException when an element is not found, so you should wrap the whole code with try/catch as the following

from selenium.common.exceptions import NoSuchElementException

try:
    element = self.driver.find_element_by_xpath(xpath)     
    if element.is_displayed():         
        raise Exception("Element should not be found")     
    else:
        print("element is not shown")
except NoSuchElementException:
        print("element doesn't exist in the tree")
Tibebes. M
  • 6,940
  • 5
  • 15
  • 36
0

To verify that the element is not present in the DOM Tree you need to induce WebDriverWait for the invisibility_of_element_located() and you can use the following logic:

try:
    WebDriverWait(driver, 20).until(EC.invisibility_of_element_located((By.XPATH, "xpath")))
    print("Element no more found")
except TimeoutException:
    print("Element should not be found")
    

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Reference

You can find a couple of relevant discussions in:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352