- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
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 −
Advertisements
To Continue Learning Please Login
Login with Google