433. Get XPath Count in Selenium WebDriver

XPath statement can be used to locate more than one element. In order to retrieve the number of elements located by a single XPath statement, we have to find out the XPath count of the specified XPath statement.

WebDriver don't have any predefined command for retrieving the XPath count like Selenium RC.
In order to retrieve the XPath count we have to use findElements(By.xpath("XPath Statement")).

So lets find an XPath statement which locates more than one element by following the below steps:

1. Open in Firefox Browser
2. In 'Firepath' tab, select XPath option and enter the XPath statement //option into the text box field as shown below:

3. So the XPath Statement //option can locate more than one element (i.e. all the list options in the drop down field)

Test Description:

Lets Implement This:


1. Create a new Java Project say 'WebDriver-Project77' in Eclipse IDE
2. Configure the Project to work with Selenium WebDriver
3. Create a package say 'package77' under the newly created project.
4. Create a Java Class file say 'Class77' under the newly created package as shown below:

Actual Steps:

1. Write the following code into the newly created Java Class file as shown below and make sure that you resolve all the errors before going to next step:

2. Create a test method 'getXPathCount()' as shown below:

3. Use findElements(By.xpath("XPath Statement")) to locate all the elements with the specified XPath and assign the located elements to List<WebElement> type variable as shown below:

4.  Write a for loop to count the number of elements located by the XPath statement (i.e. Nothing but XPath count) as shown below:

5. Enter the retrieved count into the Text Area field as shown below:

4. Save and Run the '' file by selecting the 'JUnit Test' option and ensure that our Automation Test has located all the elements which can be located with the specified xpath, counted the number of elements and enter the count into the Text Area as shown in the below video:

Watch the below video:

Click here to watch the video.

Download this Project:

Click here to download this project and import into Eclipse IDE  on your machine.

Please comment below to feedback or ask questions.

Introduction to TestNG  will be explained in the next post.

No comments:

Followers :)

Blog Index