

- 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
Test if element is present using Selenium WebDriver?
We can verify if an element is present using Selenium. This can be determined with the help of findElements() method. It returns the list of elements matching the locator we passed as an argument to that method.
In case there is no matching element, an empty list [having size = 0] will be returned. We are not using the findElement() method since if there is no matching element, this method gives NoSuchElementException.
In an event of any exception, we have to handle it with a try catch block.
Example
Code Implementation.
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import java.util.List; public class ElementPresence{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = "https://www.tutorialspoint.com/about/about_careers.htm"; driver.get(url); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); // identify element List<WebElement> l=driver.findElements(By.xpath("//*[text()='Terms of Use']")); if(l.size()== 0){ // empty list if no matching element System.out.println("Element not present, appearing "+l.size()+ " time"); } else { System.out.println("Element present, appearing "+l.size()+ " time"); } driver.quit() } }
Output
If the element is not present, the output is −
- Related Questions & Answers
- Test if an element is focused using Selenium Webdriver.
- How to verify an attribute is present in an element using Selenium WebDriver?
- Verifying whether an element present or visible in Selenium Webdriver
- C# and Selenium: Wait Until Element is Present
- How to wait until an element is present in Selenium?
- How do you click on an element which is hidden using Selenium WebDriver?
- How to run Selenium WebDriver test cases in Chrome?
- How to scroll to element with Selenium WebDriver using C#?
- Check if element is present in tuple in Python
- Find elements using Selenium WebDriver?
- Test if the HTML attribute tabindex is present and get the value
- What is WebDriver in Selenium?
- Check that the element is clickable or not in Selenium WebDriver
- Finding an element in a sub-element in Selenium Webdriver.
- How to check if an element is visible with WebDriver?
Advertisements