Selenium-6 || XPath is the best way to locate web elements.

XPath stands for XML Path, which helps us to locate any web element using its XML Path or XPath.

In the previous lesson we have learnt many ways to locate any web element like HTML Tag id, name, class name etc. When we are unable to identify using any of the mentioned way then we have to use XPath.


XPath stores values in Key-Value pair format. It uses its key to traverse through the entire web page until it doesn’t match its value. A Key is the combination of the HTML tag and it attribute. On the other hand Value is the of the attribute or attributes.

//h1[@class="page-title"]

In above example, compiler navigates through all the HTML <H1> tag which has a class attribute with value ‘page-title’.

Types of XPath

Relative XPath

Mostly this type of XPath is used while locating any web element. It finds element from the current position. We have to write relative Xpath using double slash “//” as mentioned below:
//h1[@class="page-title"]
Relative XPath

Mostly this type of XPath is used while locating any web element. It finds element from the current position. We have to write relative Xpath using double slash “//” as mentioned below:

//h1[@class="page-title"]

Absolute XPath

It starts with the document node means root of the web page. Starting point of this type is single slash “/” and we can locate element in structured manner as mentioned below:
/html/body/div/div[2]/header/h1
Absolute XPath

It starts with the document node means root of the web page. Starting point of this type is single slash “/” and we can locate element in structured manner as mentioned below:

/html/body/div/div[2]/header/h1

Difference between Absolute and Relative XPath

Absolute XPathRelative XPath
Starts from document node.Starts from current node.
Written using Single Slash “/”Written using double slash “//”
As XPath is structured, we can use Absolute XPath when there is any need to validate the structure of the webpage.As this XPath is unstructured, we can use Relative XPath to validate the presence of any web element on the page disregards its HTML structure.
It doesn’t work if HTML any of the html tag disturbed or web page structure gets changed.Sometimes we need to write complex XPath to locate any web element, which makes it difficult to understand.
Selenium Tutorials:

Window Handling: 

Test Frameworks: 

Related Links: 


Steps to Create XPath using Chrome Browser

  1. Launch the Chrome browser
  2. Navigate to http://www.allinoneblogs.com/ URL.
  3. RIght click on the web page or web element and click on Inspect option.
  4. Click on the Element section on the newly opened window.
  5. Press Ctrl+F key from keyboard, a Search Text field will appear at the bottom of the Element section tab.
  6. Now you can start writing any type of XPath, string or selector.
  7. You will observe that things getting highlighted on web page as well as on Element sections.
Get Demo to write XPath

Note: If you like the Video, hit the LIKE button and do Subscribe the Channel. Thank You!

Writing Absolute XPath

  1. Start with single slash “/”
  2. Then HTML tags depending upon the structure of the page like /html/body/div
  3. Type similar way until target element is not found on the page like /html/body/div/div[2]/header/h1

Writing Relative XPath

  1. Start with double slash “//
  2. Then type target html tag like <div>,<h1>,<a> etc. Example, //h1
  3. Now use square bracket symbol, attribute and value of the target HTML element. Example, //h1[@class=’page-title’]

Code Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

/**
 * @author ashok.kumar
 * @company allinoneblogs.com
 */
public class XpathExample {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.setProperty("webdriver.chrome.driver", "c://chromedriver.exe");
		WebDriver driver=new ChromeDriver();
		driver.get("http://www.allinoneblogs.com/");
		
		// Here two examples present for each type of XPath, please comment and uncomment the same during execution.
		
		//String absoluteXpath="/html/body/div/div[@class='page-title-container']";
		String absoluteXpath="/html/body/div/div[2]/header/h1";
		String targetString=driver.findElement(By.xpath(absoluteXpath)).getText();
		System.out.println("targetString using Absolute XPath: "+targetString);
		
		String relativeXpath="//h1[@class='page-title']";
		//String relativeXpath="//h1";
        String targetString1=driver.findElement(By.xpath(relativeXpath)).getText();
		System.out.println("targetString1 using Relative XPath: "+targetString1);
		
	}
}

Other Components of XPath

  1. Using ‘//’ or ‘/’ symbol: To define type of XPath Relative(//) and Absolute(/). Also, a single slash (/) is used to access child element of current node as well.
  2. Using ‘@’ symbol: @ used to access attribute of the HTML tag.
  3. Using ‘*’ symbol: If HTML tag is unknown we can use asterisk “*” symbol. For example, //*[@class=’allinoneblogs’]
  4. text():  To locate any web element using text instead of attribute value. For example, //h3[text()=’OUR VISION’]
  5. contains(): To locate any web element based on the partial text. For example, //h3[contains(text(),’OUR’)]
  6. starts-with(): To locate web element using the starting text. For example, //a[starts-with(@href,’http://www.allinoneblogs.com/‘)]
  7. and/or operator: To combined two or more conditions to locate any web element. For example, //a[starts-with(@href,’http://www.allinoneblogs.com/’) and contains(text(),’java’)]

Code Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

/**
 * @author ashok.kumar
 * @Company allinoneblogs.com
 */
public class XPathExample_2 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.setProperty("webdriver.chrome.driver", "c://chromedriver.exe");
		WebDriver driver=new ChromeDriver();
		driver.get("http://www.allinoneblogs.com/");
		
		// XPath using partial match of the values using contains()
		String containsXpath="//h3[contains(text(),'OUR')]";
		WebElement elem=driver.findElement(By.xpath(containsXpath));
		
		// Below method would require if Element is not visible on current screen.
		 navigateToElement(elem, driver);
		
		String headingText=elem.getText();
		System.out.println("headingText using contains(): "+headingText);
		
		// XPath using starts-with() function.
		// Get count of all links starts with given text.
		String startswithXpath="//a[starts-with(@href,'http://www.allinoneblogs.com/')]";
		int linkCount=driver.findElements(By.xpath(startswithXpath)).size();
		System.out.println("Total Links Count starts-with(): "+linkCount);
		
		// Multiple Conditions using 'and'/'or' condition
		// Get count of all the links which starts with given link and contains text 'java'.
		String multConditionXpath="//a[starts-with(@href,'http://www.allinoneblogs.com/') and contains(text(),'java')]";
		int linkCount1=driver.findElements(By.xpath(multConditionXpath)).size();
		System.out.println("Total Links contains word 'java': "+linkCount1);
		
	}
	
	public static void navigateToElement(WebElement element,WebDriver driver)
	{
		Actions action=new Actions(driver);
        action.moveToElement(element).build().perform();
	}
}

3200total visits,13visits today

Leave a Reply

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