top of page

Xpath In Selenium

 

 

What Is Xpath/XML Path In Selenium ?

​

  • Xpath is the XML path expression used for navigating through the HTML structure of  a web page to find the location of any element on a web page using HTML DOM structure.

​

  • Xpath can be used for both HTML and XML documents.

​

Basic Syntax Of Xpath :

//tag_name[@attribute_name='value of attribute'];

​

What Are The Different Types Of Xpaths ?

There are two strategies to locate any element in selenium by xpath :

  1. Absolute Xpath

  2. Relative Xpath

​

​

Absolute Xpath

​

Absolute xpath is a path that starts from the root node of XML/HTML document and navigate to the required node following one node at a time.

In this,xpath is created using a single slash '/'.

​

​

Relative Xpath

​

It's an expression which starts from the middle of DOM structure and is represented by a double slash '//' denoting the current node.

​

Note :-  Relative xpath is always preferred over absolute path because if the page changes dynamically then absolute

               path will be changed that will cause error.

​

​

Here is an example code for xpath =>

​

​

package seleniumexamples;

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

​

public class XPathExample {

​

    public static void main(String[] args) throws InterruptedException {
     
 // TODO Auto-generated method stub

        WebDriver driver;
       String
baseURL="https://www.javatpoint.com/";
       
       
//Launch the web browser
       System.setProperty("webdriver.chrome.driver","..\\SeleniumJava\\drivers\\chromedriver99.exe");
     
 driver=new ChromeDriver();
       
     
 //To maximize the size of window
       driver.manage().window().maximize();
       
     
 //Navigate through an URL
       driver.get(baseURL);
       
     
 //Locate by xpath
       driver.findElement(By.xpath("//img[@src='https://static.javatpoint.com/images/icon/python.png']")).click();
       Thread.sleep(200);
       
       
//Close the current window
       driver.close();
   }

}
 

​

​

Know More :- If you want to learn more about xpath then follow this link XPath-Axes...

​

​

Refer next page Gmail Automation Example

bottom of page