App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

Home Guide How to find element by XPath in Selenium with Example

How to find element by XPath in Selenium with Example

By Neha Vaidya, Community Contributor -

It is common knowledge by now that Selenium is the most frequently used automation testing tool. With its diversity of features, it facilitates various functionalities. One of these is the use of locators to find web elements when testing a website. Among various locators, XPath is especially useful.

This article will cover how to find Xpath in Chrome and how to utilize XPath to find web elements in automated Selenium testing.

Note: Please refer to Locators in Selenium before going forward with this article.

Introduction to XPath

XPath is a language to query XML documents. Usable on both HTML and XML documents, it allows testers to navigate through the XML structure of any document. It consists of a path expression along with some conditions.

Syntax of XPath

Below is the syntax for Xpath:

Xpath =//tagname[@Attribute=’value’]

Wherein:

  1. //: Used to select the current node.
  2. tagname: Name of the tag of a particular node.
  3. @: Used to select the select attribute.
  4. Attribute: Name of the attribute of the node.
  5. Value: Value of the attribute

To dive deeper into XPath fundamentals, study this article on Effective ways to use XPath in Selenium.

Before exploring XPath functions, let’s look at a simple example to understand.

How to find XPath in Chrome

Follow the steps below to find the XPath in Chrome.

  1. Launch Google Chrome and navigate to yahoo.com to create a yahoo account and locate the fields using XPath. Find element by Xpath
  2. Go to the First name tab and Right-click >> Inspect.
  3. On inspecting the web element, it will show an input tag and attributes like class and id.
  4. Use the id and these attributes to construct XPath, which, in turn, will locate the first name field. selenium find element by xpath
  5. Let’s write XPath in the elements tab.

Note: Use Ctrl+F to write XPath in the elements tab, as shown below.

selenium find element by xpath example

As seen above, a simple XPath is used to locate the firstName tab. Based on the XPath syntax, first use // which means anywhere in the document. Here, input is the tag name that has an id attribute with the value “usernamereg-firstname”.

On writing the XPath, it has highlighted the element, which implies that this particular element was located using XPath.

Note: One can also locate the same element using the name attribute, as it has a locator value for the name tag as well. Using the name locator, the XPath is:

//input{@name=”firstname”]

Refer to the snapshot below for clarity:

find element by xpath in Selenium

 

How to find elements by XPath in Selenium: Example

Now let’s try automating this using Selenium. Here is the Java program written in Eclipse for the same:

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class XPathexample {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "Your-Chrome-Driver-Path"); // Provide the path to your chrome driver. Make sure your chrome driver version is updated.
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("https://login.yahoo.com/account/create");
driver.findElement(By.xpath("//input[@id='usernamereg-firstName']")).sendKeys("Your-Name"); // Will send values to First Name tab
}
}

On executing the code above, Chromedriver will launch Google Chrome, navigate to Yahoo signup page and enter the value for first name tab as shown below.

Similarly, fill in all the details and find elements by XPath in Selenium.

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class XPathexample {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "Your-Chrome-Driver-Path"); // Provide the path to your chrome driver. Make sure your chrome driver version is updated.
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("https://login.yahoo.com/account/create");
driver.findElement(By.xpath("//input[@id='usernamereg-firstName']")).sendKeys("Your-Name"); // Will send values to First Name tab
driver.findElement(By.xpath("//input[@id='usernamereg-lastName']")).sendKeys("Your-Last_name"); //xpath for last name box
driver.findElement(By.xpath("//input[@id='usernamereg-yid']")).sendKeys("email@yahoo.com"); //xpath for email box
driver.findElement(By.xpath("//input[@id='usernamereg-phone']")).sendKeys("123456789"); //xpath for phone number box
driver.findElement(By.xpath("//select[@id='usernamereg-month']")).click(); //xpath for usermonth box
driver.findElement(By.xpath("//input[@id='usernamereg-day']")).sendKeys("01"); //xpath for userday box
driver.findElement(By.xpath("//input[@id='usernamereg-year']")).sendKeys("1999");// xpath for user year
driver.findElement(By.xpath("//button[@id='reg-submit-button']")).click();// xpath for submit button
}
}

On executing the above code, it will fill in all the details and hit the Continue button to complete the form submission.

Run Selenium Tests on Real Devices for Free

While this post has discussed a variety of ways to locate elements on a web page using the XPath locator in Selenium Webdriver, one should use Occam’s razor – the simplest and logical options while selecting elements to ensure minimal rework in the event of a page redesign.

Try running the code detailed above using Selenium. Bear in mind that Selenium tests must be run on a real device cloud instead of emulators or simulators to get completely accurate results. BrowserStack’s cloud Selenium grid of 3000+ real browsers and devices allows testers to automated visual UI tests in real user conditions. Simply sign up, select a device-browser-OS combination, and start running tests for free.

Tags
Automation Testing Selenium Selenium Webdriver

Featured Articles

Quick XPath Locators Cheat Sheet

How to use XPath in Selenium? (using Text, Attributes, Logical Operators)

Curated for all your Testing Needs

Actionable Insights, Tips, & Tutorials delivered in your Inbox
By subscribing , you agree to our Privacy Policy.
thank you illustration

Thank you for Subscribing!

Expect a curated list of guides shortly.