

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Questions & Answers
- 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
- Check if a particular element exists in Java LinkedHashSet
- How to find if element exists in document - MongoDB?
- How to wait until an element no longer exists in Selenium?
- How to check if event exists on element in jQuery?
- How to check if onClick exists on element in jQuery?
- How to check if element exists in the visible DOM?
- Check if subarray with given product exists in an array in Python
- Check if a triplet with given sum exists in BST in Python
- Test if element is present using Selenium WebDriver?
- Java Program to check if a particular element exists in HashSet
Advertisements