Find Element by XPath: A Complete Guide

Find Element by XPath: A Complete Guide

The browser renders web pages as HTML documents, HTML documents contain a series of HTML elements such as <body> <div> <title> <p> etc. Automation Testing of web applications requires components of the webpages to be identified uniquely to perform any action on that. Locators or Selectors are used to identify the web elements uniquely on the webpage. The Locators are a series of elements chained with the selector-specific syntaxes. However, every automation tool provides its own method to find element by XPath.Selectors can be broadly classified into,

  • CSS selectors
  • XPath

The XPath selector is the most commonly used selector and is supported by all major browsers and test automation tools.

What is XPath?

XPath stands for XML Path Language. It is an XML Path notation used for navigation throughout the HTML document of the page. It uses the XML-based syntax to find the HTML element on the webpage. XPath is also known as a query language. The XPath works for any complicated application. General Syntax for XPath is as follows.

For example, you can construct XPath,

  • //: Selects the current node.
  • Tag name: Name of the tag.
  • @: Select the attribute.
  • Attribute Name: Name of the attribute.
  • Value: Value of the attribute.

Types of XPath

  • Absolute XPath: The absolute XPath starts with a single slash (/) and starts with the root element. The absolute XPath is not recommended. There is a high chance to break the XPath when there are any changes in the application DOM tree.
  • Relative XPath: The relative XPath starts with a double slash(//), typically it begins in the middle of the HTML DOM tree. It is the most recommended approach as it is highly effective and reliable.

XPath Methods

Advanced XPath syntax provides different methods. You can also use these methods inside the XPath such as Text(), Contains(), Startswith(), etc.

  • Text(): The Text() method helps to locate the XPath based on the text attached to the specific element.
  • Contains (): This method helps to construct the XPath with partial match. That can be the value of the text, the value of the attribute, etc.
  • Startswith(): As the name indicates you can construct the XPath by starting the string of attribute values.
  • AND&OR: Conditional Matching is one of the advanced operations that can be performed on XPath. You can use the “AND” and “OR” operators inside the XPath. The “AND” and “OR” evaluation works according to the logical truth table.

XPath Axes methods

The XPath supports complicated relationship establishment across the elements in the DOM tree. The axes method also helps to establish the relationship in the DOM tree elements. That can be parent, siblings, ancestor, child, following and dependent, etc.

How to find element by XPath in Chrome

The XPath is supported by most modern browsers. Browsers like Chrome allow us to write the XPath in the developer tools and check the correctness. If your XPath is correct, then chrome highlights the specific web element in UI.

Let’s discuss how to write the XPath in Chrome Browser,Let’s take the above-mentioned scenario of finding the XPath for <ul> that contains the list of product menu.

1. Navigate to the Webpage.

You can Navigate to any webpage you wish, for simplicity let’s navigate to https://testsigma.com/.


2. Right Click on the desired element in our case its footer element and Click on Inspect.


inspect

Ensure the Chrome DevTools opens with the Elements tab Activated.3. Use the Ctrl+F key to bring the Search Input into the dev tools4. Construct the XPath using the XPath rules.XPath follows certain syntaxes mentioned above; it may start with / or //, and you need to follow XPath syntax.

Now, you need to find the list of the footer links using XPath. You have a ul tag associated with li, which can be constructed as shown below.


find element by xpath

Wildcards in XPath

XPath allows us to use wild cards such as * (asterisk),. (dot), @*, etc.

  • * (asterisk): is used to match any node in the document.
  • .(dot): is used to match the current node in the context.
  • @*: is used to match any attribute.
  • node(): is used to match any node type.

Many modern automation tools like TestSigma don’t require you to construct the XPath. It makes the locator strategy hassle-free. For example, if you are using TestSigma you can simply record the test cases using the recorder tool. It automatically captures relevant locators. Later, if you wish you can manually edit the locators. If you have a test automation framework ready, the locator construction part is the most time-consuming and requires a certain level of technical knowledge. However, Testsigma does it for you with no pain.

XPath in Selenium

Selenium is an open-source test automation tool built for browsers. Selenium supports multiple languages and browsers however Selenium Java is the most popular and widely used. Selenium provides a method to use all possible locators, such as CSS or XPath-based selectors.

For example, selenium allows finding the element by ID, XPath, TagName, Class Name, etc. Selenium find element by XPath is the most widely used. It works even if none of the other locators works. The FindElement() is the base method for any Selenium locator, like finding the element by XPath.

FindElement by XPath in Selenium

The FindElement and FindElements are two different methods that help to find the element in the webpage, by using the locator strategies.

FindElement in Selenium: The FindElement method returns the WebElement object which contains the element of the webpage. It returns the Single element so it is more suitable when you are acting on a single web element. When you execute the FindElement() logic on the browser, it searches for the matches based on the locator Strategy. Returns you the first locator that matches.

FindElements in Selenium: Unlike the FindElement method, the FindElements method returns multiple elements as a list (List<WebElement>) so it is more appropriate when you want to perform the operation on a series of web elements.

Find ElementFindElements
Returns the Single Element of Type WebElementReturns the multiple web element of type List<WebElement>
Returns First most web element if there are multiple matchesReturns the list of web elements
Cannot iterate over multiple elementsHelps to iterate over multiple elements and perform an action on them
If there is no Element NoSuchElementException is thrownReturns the empty list if no matching element is found
Since there is only one element cannot access the element by indexIf there are multiple elements we can access the element by using index. The index starts from 0, 0th index returns the first web element

FindElement by XPath Detailed Guide

The below example shows the usage of findElement using Java.

  • driver: the driver is an instance of Selenium Webdriver
  • findElement: The Find Element method requires Locator Strategy as the parameter.

Selenium Locator Strategies

List of selenium locators:

  • ID.
  • Name.
  • Class Name.
  • Tag Name.
  • Link Text.
  • Partial Link Text.
  • XPath.

The above is the list of selenium locator strategies. Based on the webpage and availability of the locator strategy choose the right one.

For example, if you would like to find element by XPath you can simply write the code below,

WebElement element = driver.findElement(By.XPath(“//div[@id=’myid’]”));

Later, once you get the element you can directly perform the action on it such as click, type, etc.

Example:

WebElement element = driver.findElement(By.XPath(“//div[@id=’myid’]”)); element.click();

Find Elements in Selenium

As the name indicates, the findElements returns multiple web elements as a List. This method fetches multiple elements at once and performs iterative operations on them.

Find Elements in Selenium Code Example

Syntax:

Later, once you get the element you can directly perform the action on it such as click, type, etc.

Example:

WebElement element = driver.findElement(By.XPath(“//div[@id=’myid’]”)); element.click();

Find Elements in Selenium

As the name indicates, the findElements returns multiple web elements as a List. This method fetches multiple elements at once and performs iterative operations on them.

Find Elements in Selenium Code Example

Syntax:

  • Driver: The driver is an instance of the Selenium Webdriver.
  • FindElements: A method in selenium, requires the LocatorStrategy as parameters.
  • Returns the List containing the Web elements.

Example:

Let’s consider we have a list of footer links, and we wanted to fetch all the links at once and get the text. Then we can construct find elements by XPath like below,

footer links


Using FindElement(s) by XPath in Selenium.

As mentioned above selenium provides the FindElement(s) method to fetch the locator from the webpage. You can use this method with the driver by passing the Locator strategy as a parameter.

Let’s understand it with a simple scenario.

  1. Navigate to Testsigma.
  2. Find the footers in the footer section.
  3. Log the Text of the footers.

To write the above scenarios in Selenium we need to follow different steps. Let’s take a look one by one.

Create a web driver object

Navigate to webpage

Find the footer Element which is having the list of items.

As discussed in the Chrome XPath section, the ul and li holds the list of product menu items.

Let’s construct XPath for the same,

Once you have the XPath, pass this XPath as a locator strategy for the Find Element by XPath method. Example:

Log the text value of the element

To log the text value of the element, you need to iterate over each element and log it.

Putting everything together, below is a code example to find element by XPath.


Test automation made easy

Start your smart continuous testing journey today with Testsigma.

SHARE THIS BLOG

RELATED POSTS


Power of POC in Testing: Your Exclusive Guide to Success
Power of POC in Testing: Your Exclusive Guide to Success
Sitecore Automated Testing What it is and How to Perform
Sitecore Automated Testing | What it is and How to Perform?
Software Testing Tools_banner image
Retail Application Testing | What it is & Why it’s Necessary?