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"]
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 XPath | Relative 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:
- Selenium-1 || Understanding Selenium and Selenium WebDriver.
- Selenium-2 || Let’s learn Selenium IDE.
- Selenium-3 || First program using Selenium Web Driver.
- Selenium-4 || Handling multiple web browsers.
- Selenium-5 || Locating web elements using various type of Locators.
- Selenium-6 || XPath is the best way to locate web elements.
- Selenium-7 || Let’s learn to create complex XPath.
- Selenium-8 || Implementing Wait(s) in Selenium.
- Selenium-9 || Understanding WebDriver API.
- Selenium-10 || Taking Screenshots using Selenium
- Selenium-11 || Use of Actions and Action Classes.
- Selenium-12 || Select Class to handle drop-down.
- Windows Handling | Multiple windows handling using JavascriptExecutor.
- iFrame || Multiple ways to handle iFrame html tag using selenium.
- iFrame || iFrame Handling within a web page.
- getWindowHandle() and getWindowHandles() methods.
- Properties File | Accessing properties file for user input or test data.
- Framework || Simple example of Key Driven Framework using excel sheet in Selenium(JAVA).
- TestNG – 16 || Access data from Excel sheet using DataProvider.
- Selenium Grid | Configuration and implementation with Example.
- TestNG – 1 || Introduction and benefits of TestNG Framework.
- TestNG – 2 || Installation process and a sample program of TestNG.
- TestNG – 3 || Create and execute multiple Test Cases.
- TestNG – 4 || Let’s understand @Test Annotation and attributes.
- TestNG – 5 || Understand Assertion in TestNG.
- TestNG – 6 || Use of @BeforeMethod and @AfterMethod.
- TestNG – 7 || Use of @BeforeClass and @AfterClass.
- TestNG – 8 || Creation and execution of Test Suites.
- TestNG – 9 || Let’s move deep into the Test Suites.
- TestNG – 10 || Use @BeforeTest and @AfterTest Annotations.
- TestNG – 11 || Groups attribute with @Test Annotation.
- TestNG – 12 || Use of @BeforeGroups & @AfterGroups.
- TestNG – 13 || Use of @BeforeSuite & @AfterSuite.
- TestNG – 14 || DataProvider annotation & attribute.
- TestNG – 15 || DataProvider with parameters.
- TestNG – 16 || Access data from Excel sheet using DataProvider.
- TestNG – 17 || Passing multiple Parameters in testng xml.
- TestNG – 18 || Multiple Browser and Parallel Execution in TestNG.
- TestNG -19 || Concept of Parallel Execution.
- TestNG – 20 || Run TestNG Program using main() method.
- Headless Testing via ChormeOptions Class.
Steps to Create XPath using Chrome Browser
- Launch the Chrome browser
- Navigate to http://www.allinoneblogs.com/ URL.
- RIght click on the web page or web element and click on Inspect option.
- Click on the Element section on the newly opened window.
- Press Ctrl+F key from keyboard, a Search Text field will appear at the bottom of the Element section tab.
- Now you can start writing any type of XPath, string or selector.
- You will observe that things getting highlighted on web page as well as on Element sections.
Note: If you like the Video, hit the LIKE button and do Subscribe the Channel. Thank You!
Writing Absolute XPath
- Start with single slash “/”
- Then HTML tags depending upon the structure of the page like /
html /body/div - Type similar way until target element is not found on the page like /html/body/div/div[2]/header/h1
Writing Relative XPath
- Start with double slash “//”
- Then type target html tag like <div>,<h1>,<a> etc. Example, //h1
- 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
- Using ‘//’ or ‘/’ symbol: To define
type of XPath Relative(//) and Absolute(/). Also, a single slash (/) is used to access child element ofcurrent node as well. - Using ‘@’ symbol: @ used to access attribute of the HTML tag.
- Using ‘*’ symbol: If HTML tag is unknown we can use asterisk “*” symbol. For example, //*[@class=’allinoneblogs’]
- text(): To locate any web element using text instead of attribute value. For example, //h3[text()=’OUR VISION’]
- contains(): To locate any web element based on the partial text. For example, //h3[contains(text(),’OUR’)]
- starts-with(): To locate web element using the starting text. For example, //a[starts-with(@href,’http://www.allinoneblogs.com/‘)]
- 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();
}
}