
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 by XPath in Selenium
The findElement(By.xpath) method is used to identify an element which matches with the xpath locator passed as a parameter to this method. The findElements(By.xpath) method is used to identify a collection of elements which match with xpath locator passed as a parameter to that method.
The method findElement(By.xpath) returns a web element whereas the method findElements(By.xpath) returns a list of web elements. An exception is thrown by the method findElement(By.xpath) if there is no matching element. An empty list of elements is returned if there is no matching element obtained from the findElements(By.xpath) method.
Let us try to identify the number of children of the ul tag and also the first subelement of ul( li[1] having text Selected Reading).
Syntax
List<WebElement> n = driver.findElements(By.xpath("//ul[@class=' toc reading']/li")); WebElement m =driver.findElement(By.xpath("//ul[@class=' toc reading']/li[1]"));
Example
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.concurrent.TimeUnit; import java.util.List; public class XpathFindElment{ public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("https://www.tutorialspoint.com/about/about_careers.htm"); // identify elements with findElements xpath List p = driver.findElements(By.xpath("//ul[@class='toc reading']/li")); //count of list of matching elements int s = p.size(); //identify element with xpath WebElement m = driver.findElement(By.xpath("//ul[@class='toc reading']/li[1]")); System.out.println("Element text is: "+ m.getText()); driver.quit(); } }