Why to use xpath in Selenium

Author - Namisha Arora

What is Xpath?

Xpath is defined as XML path. If we are unable to find an element with id, class or name locator  on web page then we can use XML path expression for finding the element on a webpage.

Syntax to write xpath is:

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

// : double slash means you are selecting the current node
Tagname: tagname means any input like div
@ : it means select the attribute
Attribute: it means the name of the node
Value: It means the value of the attribute
Xpath is of two types:

1. Absolute Path: It uses complete path from the root element to desired element. It is called complete or full XPath. It starts from HTML tag name and the single slash (/). We can generate it using Firebug and Firepath.

For Example: html/body/div[1]/section/div[1]/div/div/div/div[1]/div//div[1]/div/h1[2]/b

2. Relative Path: It starts from the middle of the HTML DOM structure. It starts from double forward slash (//) which means it searches element anywhere on the webpage. It is also called as short path because using it we don’t need to write long path.

For Example:  //*[@id=drop-down]//*[text()=’Testing’]

Below is the example of using Xpath:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
import java.util.concurrent.TimeUnit;

public class test {
public static void main(String[] args) {
WebDriver driver;

//This will launch the Firefox browser
driver = new FirefoxDriver();
//open the url in browser
//maximize the screen
//Relative xpath of Featured Courses page link
Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *

Send your message