The best VPN 2024

The Best VPS 2024

The Best C# Book

How to find element by XPath in Selenium?

Spread the love

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.

How to find element by XPath

This article will examine Xpath, and how to utilize it to find web elements in automated Selenium testing.

Below topics are covered in this article:

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 elements by XPath in Selenium: Example

This example will launch Google Chrome and navigate to yahoo.com to create a yahoo account. The intent is to locate the fields using XPath.

How to find element by XPath in Selenium?
How to find element by XPath
  1. Go to the First name tab and right click >> Inspect.
  2. On inspecting the web element, it will show an input tag and attributes like class and id.
  3. Use the id and these attributes to construct XPath which, in turn, will locate the first name field.
How to find element by XPath
How to find element by XPath

Let’s write XPath in the elements tab.

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

How to find element by XPath
How to find element by XPath

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 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:

How to find element by XPath
How to find element by XPath

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
}
}

How to find element by XPath

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.

continue
How to find element by XPath

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
}
}

How to find element by XPath

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

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 to get completely accurate results. BrowserStack’s cloud Selenium grid of 2000+ 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.

Reference: https://www.browserstack.com/guide/find-element-by-xpath-in-selenium

Leave a Comment