- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Checking if element exists with Python Selenium.
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
- Related Articles
- Check if any alert exists using selenium with python.
- How to check if Element exists in c# Selenium drivers?
- Checking if a key exists in HTML5 Local Storage
- Checking if a key exists in a JavaScript object
- Check if element exists in list of lists in Python
- Python Program to Test if any set element exists in List
- How to wait until an element no longer exists in Selenium?
- Screenshot of a particular element with Python Selenium in Linux
- Check if a particular element exists in Java LinkedHashSet
- How to find if element exists in document - MongoDB?
- Checking HTTP Status Code in Selenium.
- How to get coordinates or dimensions of element with Selenium Python?
- How to identify nth element using xpath in Selenium with python?
- How to check if event exists on element in jQuery?
- How to check if onClick exists on element in jQuery?

Advertisements