Selenium Locators - XPath


XPath is defined as XML path.
It is a syntax or language for finding any element on the web page using XML path expression. 
XPath is used to find the location of any element on a webpage using HTML DOM structure.
XPath can be used to navigate through elements and attributes in DOM. 

In this article we will disccuss
1) What is XPath?
2) What is DOM?
3) Types of XPath ( Absolute & Relative)
4) Diff between Absolute & Relative xpaths 
5) How to capture XPaths - Extensions for chrome
6) Which XPath is preferred? Why?
7) XPath options
  •    or
  •    and
  •    contains()
  •    starts-with()
  •    text()
  •    chained xpath



Example:
-----------------

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

public class LocatorsDemo4_XPaths {

public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver","C://Drivers//chromedriver_win32//chromedriver.exe");

WebDriver driver=new ChromeDriver();

driver.get("http://automationpractice.com/index.php");
driver.manage().window().maximize();

//Absolute xpath
//driver.findElement(By.xpath("/html[1]/body[1]/div[1]/div[1]/header[1]/div[3]/div[1]/div[1]/div[2]/form[1]/input[4]")).sendKeys("T-shirts");
//driver.findElement(By.xpath("/html[1]/body[1]/div[1]/div[1]/header[1]/div[3]/div[1]/div[1]/div[2]/form[1]/button[1]")).click();

//Relative xpath
//driver.findElement(By.xpath("//input[@id='search_query_top']")).sendKeys("T-shirts");
//driver.findElement(By.xpath("//button[@name='submit_search']")).click();


//xpath with   'or'

//driver.findElement(By.xpath("//input[@id='search_query_top' or @name='search_queryX']")).sendKeys("T-shirts");
//driver.findElement(By.xpath("//button[@name='submit_searchX' or @class='btn btn-default button-search']")).click();

//xpath with 'and'
//driver.findElement(By.xpath("//input[@id='search_query_top' and @name='search_query']")).sendKeys("T-shirts");
//driver.findElement(By.xpath("//button[@name='submit_search' and @class='btn btn-default button-search']")).click();

//xpath with contains()
//driver.findElement(By.xpath("//input[contains(@id,'query_top')]")).sendKeys("T-shirts"); // id=search_query_top
//driver.findElement(By.xpath("//button[contains(@name,'search')]")).click(); // name=submit_search

//xpath with start-with()
//driver.findElement(By.xpath("//input[starts-with(@id,'search_query')]")).sendKeys("T-shirts"); // id=search_query_top
//driver.findElement(By.xpath("//button[starts-with(@name,'submit_')]")).click(); // name=submit_search

//xpath with text()
//driver.findElement(By.xpath("//a[text()='Women']")).click();   // WOMEN Tab

//chained xpath

driver.findElement(By.xpath("//form[@id='searchbox']//input[@id='search_query_top']")).sendKeys("T-shirts");
driver.findElement(By.xpath("//form[@id='searchbox']//button[@name='submit_search']")).click();


}

}

Followers