testsigma
Topics
left-mobile-bg

Find Element by XPath: A Complete Guide

July 22, 2024Priyanka
right-mobile-bg
Find Element by XPath: A Complete Guide
image

Start automating your tests 10X Faster in Simple English with Testsigma

Try for free

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.

//tagname[@attribute=’value’]

For example, you can construct XPath,

//div[@id=’myid’]
  • //: Selects the current node.
  • Tag name: Name of the tag.
  • @: Select the attribute.
  • Attribute Name: Name of the attribute.
  • Value: Value of the attribute.

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.

//footer[@class=’footer sec_padding’]//div[@class=’footer_items’]/ul/li
find element by xpath

For example, as you can see in the above screenshot. First <li> is highlighted and in the search box you can see there are 18 matches. There are 18 different links in the list.

You need to follow the same steps for other browsers also. As mentioned before, most of the modern browser supports XPath. You can also use Edge, Firefox, Chromium, or any similar browsers.

Automate your tests for Web, Mobile, Desktop and APIs on Cloud with Testsigma. No setup required.

Try for free

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.

WebElement element = driver.findElement(By.LocatorStrategy(“SelectorValue”));
  • driver: the driver is an instance of Selenium Webdriver
  • findElement: The Find Element method requires Locator Strategy as the parameter.

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:

List<WebElement> elementList = driver.findElements(By.LocatorStrategy(“Selector”));
  • 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
List<WebElement> links = driver.findElements(By.XPath(“//footer[@class=’footer sec_padding’]//div[@class=’footer_items’]/ul/li “));

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

WebDriver driver = new ChromeDriver()

Navigate to webpage

driver.get(“https://testsigma.com/ “);

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,

XPath: //footer[@class=’footer sec_padding’]//div[@class=’footer_items’]/ul/li

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

List<WebElement> elements =driver.findElements(By.XPath(“//footer[@class=’footer sec_padding’]//div[@class=’footer_items’]/ul/li “));

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.

import java.util.List;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class SeleniumXPath {
@Test
public void seleniumDemoTest() {
WebDriver driver = new ChromeDriver();
driver.get(“https://www.testsigma.com”);
driver.switchTo().frame(“iframeResult”);
List elements = driver.findElements(By.XPath(“//footer[@class=’footer sec_padding’]//div[@class=’footer_items’]/ul/li “));
for (WebElement element : elements) {
System.out.println(element.getText());
}
}
}

The above example illustrates the Selenium Find Element by XPath. Similarly, you can use the Selenium findElement by ID.

Build and run tests 10x faster for web, mobile, desktop and APIs under Testsigma’s unified platform.

Try for free

Frequently Asked Questions

What is XPath?

XPath is XSLT standard element. It can be used to navigate elements in XML or HTML DOM contents.

What is Absolute XPath?

Absolute XPath is the least used XPath type; it starts from the root of the HTML DOM tree. Absolute XPath Starts with a single slash (/).

What is Relative XPath?

Relative XPath is the most used XPath type; it starts with a double slash (//).

There are different types of locator strategies available in Selenium, such as ID, class, name, Link text, and XPath. However, various experts suggest using the XPath when there are no other locators available to use. One of the reasons is – typically, XPath is associated with more than one HTML elements, so any new functionality can break the existing XPath.

How to find the XPath Value?

Any modern browser’s developer tools can help to find the XPath value; there are third-party plugins that can help you to find the XPath easily. However, the browser dev tools can help you in most of the scenarios.

How to find the XPath by Text?

The XPath can also be constructed to find text in the DOM element. In such cases, you need to use the text() functions in the XPath.Example://ul/li[text()=’banana’].

Automated Testing https://testsigma.com/automated-testing Scriptless Test Automation
Scriptless Test Automation | What , Why it Matters & Examples
Codeless Testing Tools https://testsigma.com/codeless-automation-testing-tools
imageimage
Subscribe to get all our latest blogs, updates delivered directly to your inbox.

RELATED BLOGS


Types of Testers: A Comprehensive Guide 
RAHUL PARWAL
AUTOMATION TESTING
Automated Test Oracles in Software Testing
KIRUTHIKA DEVARAJ
AUTOMATION TESTING
Accelq vs Provar | Which One You Should Choose?
TESTSIGMA ENGINEERING TEAM
AUTOMATION TESTING