Checking if element exists with Python Selenium.

SeleniumAutomation TestingTesting Tools

We can check if an element exists with Selenium webdriver. There are multiple ways to achieve this. We can introduce a try / except block. In the except block, we shall throw the NoSuchElementException in case the element does not exist on the page.

We can also verify if an element is present in the page, with the help of find_elements() method. This method returns a list of matching elements. We can get the size of the list with the len method. If the len is greater than 0, we can confirm that the element exists on the page.

Example

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/index.htm")
#try except block
try:
#identify element
l= driver.find_element_by_css_selector("h4")
s= l.text
  print("Element exist -" + s)
#NoSuchElementException thrown if not present
except NoSuchElementException:
print("Element does not exist")
driver.close()

Example

from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/index.htm")
#identify element
l= driver.find_elements_by_css_selector("h4")
#get list size with len
s = len(l)
# check condition, if list size > 0, element exists
if(s>0):
   m= l.text
print("Element exist -" + m)
else:
   print("Element does not exist")
driver.close()

Output

raja
Published on 18-Sep-2020 08:49:17
Advertisements