
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Find Element and FindElements in Selenium
The methods findElement and findElements are used to identify elements on the webpage. Both these methods can be used with locators like id, css, class, name, xpath, css, link text, tagname and partial link text.
The method findElement is used to identify an element which matches with the locator (used with By object) passed as a parameter to that method. If there is no matching element, then NoSuchElementException is thrown.
The method findElements is used to identify a list of elements which matches with the locator (used with By object) passed as a parameter to that method. If there is no matching element, an empty list is returned.
The method findElement returns a webelement while the method findElements returns a list. If there are multiple elements which match with the locator, then the findElement method will only return the first matching element (starting from the top left in the page).
Syntax
List<WebElement> e = driver.findElements(By.className("txt")); WebElement elm = driver.findElement(By.className("txt"));
Example
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 ElementLocator{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("https://www.tutorialspoint.com/index.htm"); //identify all links with findElements List m = driver.findElements(By.tagName("a")); //link counts int st = m.size(); System.out.println("Number of links: " + s); //identify a link WebElement n = driver. findElement(By.xpath("//a[@title='Job @ Tutorials Point']")); //get link text String s= n.getText(); System.out.println("Text is : " + s); driver.quit(); } }