Saturday, June 22, 2024

XPath and Types of XPath

 

XPath: Identifying and Navigating Elements in HTML

XPath (XML Path Language) is a powerful tool for identifying and navigating elements in an HTML document.

It allows you to traverse from one element to another in a structured way.

It can be used to identify ele/tag or navigate to ele in html doc/page

// navigate from one ele to another ele

   traverse from one ele to another ele

 

 

Types of XPath:

1. Absolute XPath (Complete XPath):

  • Definition: Always starts from the root node (i.e., the <html> tag).

·        (html - root ele or root node or root tag)

  • Starts with: /

Writing Absolute XPath:

Steps to Write XPath:

  1. Inspect the element:
    • Right-click on the target element and select "Inspect".
    • Press Ctrl + F to display a textbox where you can write XPath expressions.
  2. Start from the root node:
    • Locate the <html> tag in the HTML document.

Examples:

·        Find the <html> tag:

xpath
    • Output: 1 element found.

·        Navigate to the <head> tag from the <html> tag:

xpath
    • Output: 1 element found.

·        Navigate to the <body> tag from the <html> tag:

xpath
    • Output: 1 element found.

·        Navigate to a non-existent <b> tag within the <body> tag:

xpath
    • Output: 0 elements found (since there are no <b> tags inside <body>).

·        Navigate to all <input> tags within the <form> tag:

xpath
    • Output: 12 elements found (assuming there are 12 <input> tags inside the <form> tag).

·        Navigate to the first <input> tag within the <form> tag:

xpath
    • Output: 1 element found (the first <input> tag).

·        Navigate to the second <input> tag within the <form> tag:

xpath
    • Output: 1 element found (the second <input> tag).

·        Navigate to the third <input> tag within the <form> tag:

xpath
    • Output: 1 element found (the third <input> tag).

·        Navigate to a non-existent 17th <input> tag within the <form> tag:

xpath
    • Output: 0 elements found (since there are fewer than 17 <input> tags).

Note:

To copy the full XPath of an element:

  • Right-click on the target element.
  • Select "Copy full XPath".

 

find 'html' tag in html page--> /html    -   1 ele found

 

navigate to "head" tag from "html" tag --> /html/head      -  1 ele

 

navigate to "body tag from "html" tag -->/html/body   - 1 ele

 

navigate to 'b' tag from "body" tag --> /html/body/b - 0 ele found

    -  0  ele with body tags - goes body tag  -  search for all 'b' tags --   0 ele

 

Navigate to all input tags -->  /html/body/form/input

  - 12 ele  -- search for all input tags in form tag

 

navigate to 1st input tag in form tag --> /html/body/form/input[1]

navigate to 2nd input tag in form tag --> /html/body/form/input[2]

navigate to 3rd input tag in form tag --> /html/body/form/input[3]

 

navigate to 17th input tag in form tag --> /html/body/form/input[17] - 0 ele

--  0 ele  as we dont have 17 th "input" tag in "form" tag

 

Note:

copy full xpath   from html page  >  right click on target ele ->  Copy full xpath

 

 

code :

package WebelementsBasics;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class TextboxAbsoluteXpath {

 

            public static void main(String[] args) {

                        //open chrome browser

                        System.setProperty("webdriver.chrome.driver", ".\\Drivers\\chromedriver.exe");

                        WebDriver  driver =  new ChromeDriver();

 

                        // open url file:///C:/brahma/Practise/SelniumPractiseNew/SampleWebpage.html

                   driver.get("file:///C:/brahma/Practise/SelniumPractiseNew/SampleWebpage.html");

 

 

                        //how to use  Absolute xpath

                        // enter some value in "first name" text box  by using absolute xpath

                        WebElement  firstNameTxtboxEle = driver.findElement(By.xpath("/html/body/input[1]"));

                        firstNameTxtboxEle.sendKeys("Rama");

 

                        // enter some value in "Last name" textbox  by using absolute xpath

                        driver.findElement(By.xpath("/html/body/input[3]")).sendKeys("Rao");

 

                        // HW  Enter some value in "new" text box using absolute xpath

 

                        // HW Enter some value in 'middle name'  textbox using absolute xpath

 

 

                        // Note:  SessionNotcreatedException :   when browser version and chromedriver.exe file version are different, then it throws

                        // SessionNotcreatedException

                        // When we get this excpetion,  we have to check chrome browser version  and download repective chromedriver version.

                        //  chrome browser 103  version --   download chromdriver.exe file 103 version

                        //  104  -->   104 version

 

 

            }

 

}

 

                                               

Disadvantages of Absolute XPath:

1. Fragility to Structure Changes:

Absolute XPath specifies the exact path from the root element to the target element. This approach has significant drawbacks:

·        Dynamic Structure: If developers add, remove, or reorder elements within the HTML structure, the indices used in Absolute XPath may change. For instance:

 

<input type="text"   --> input[1]

<input type="text"   --> input[2]

 

<input type="text"   --> input[3]  -- developer adds new tag

<input type="text"    --> input[4]

 

 

2. Absolute XPath expressions are often lengthy because they start from the root node (/html) and traverse through each nested element

            /html/body/input[4]

 

3.  always we have to start from root element/tag to the desired tag.

 

    cannot navigate directly to desire tag / ele

 

HW Write absolute xpath :   for pwd , new password, male radio. female radio, Computers checbox, links, Image...

 

HW WAP Handle PWd, new password, male radio. female radio, Computers checbox, links, Image  using absolute xpath ?

 

Note :  we don’t prefer writing absolute xpath in Real time Projects

 

2. Relative XPath (or) Custom XPath (or) User-defined XPath:

Relative XPath can start from any element within the document structure.

    starts from any tag (or) in the middle of html page

 

Syntax:

//tagname[@AttributeName='AttributeValue']\

 or

//tagname[@AttributeName=”AttributeValue”]

Double Slash (//): Indicates that the search can start from anywhere in the document, not necessarily from the root.

 ---------------------

 -->  

xpath for "firstName" textbox:

---------------------------

<input type="text" name="fname" id="fid" class="firstclass">

 

firstname textbox - xpath using 'name' attribute -->  //input[@name= 'fname']

firstname textbox - xpath using 'id' attribute"  -->  //input[@id='fid']

firstname textbox - xpath using 'class' attribute" --> //input[@class = 'firstclass']       2 - ele  found

 

 //input[@name='fname']  - goes to html page and searches for all input tags where name = "fname" -

 

//input[@id='fid'] -goes to html page and searches for all input tags where id='fid' --

 

firstname textbox --> //input [@class='firstclass'][1]  1 ele

 

 

xpath for "LastName" textbox:

----------------------------

 

<input type="text" name="lname" id="lid" class="firstclass">

 

Syntax: //tagname[@AttrName = 'AttrValue']  (or) //tagname[@Attrname= "AttriValue"]

 

write xpath using id -->  //input[@id='lid']  1 ele found

write xpath using  name-->  //input[@name='lname']  -1 ele found

write xpath using class -->  //input[@class='firstclass']    - 2 ele found

 

//input[@class='firstclass'][2]  - 1 ele found

 

 

HW  write relative xpath for Middle name, User name

 

code:

-----

package WebelementsBasics;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class TextboxRelativeXpath {

 

            public static void main(String[] args) {

                        //open chrome browser

                        System.setProperty("webdriver.chrome.driver", ".\\Drivers\\chromedriver.exe");

                        WebDriver  driver =  new ChromeDriver();

                   driver.get("file:///C:/brahma/Practise/SelniumPractiseNew/SampleWebpage.html");

 

                        //how to use  Relative xpath

                        // enter "Ramu" in "first name" text box by using Relative xpath (name)

                        driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("Ramu");

 

                        // enter "yadhav" in "Last name" textbox  by using Relative xpath(name)

                        driver.findElement(By.xpath("//input[@name='lname']")).sendKeys("Yadhav");

 

 

                        // HW  Enter some data in 'Middle name'  and 'user name'  text box using relative xpath ?

 

 

 

 

 

            }

 

}

 

 

 

Hw Handle 'Password' using Xpath:

 

HW Handle 'Radio button' using Relative Xpath:

 

                        //HW Click 'male' Radio btn  using Relative Xpath

 

                        //HW get radio  button 'male' status selected  using Relative Xpath

                        //  isSelected()

 

                        //HW get radio  button 'female' status   using Relative Xpath

 

------------------------------------

HW click checkboxes 'Electronics',  Computers,  Civil   use Relative Xpath

          click

        is selected

            is displayed

            is enabled

            get attribute value  name, id ....

 

 

// HW Click 'My gmail' link using Relative Xpath   

 

 

//HW  click Login button using Relative Xpath?

 

// HW get url of 'My gmail' link using xpath

 

XPath with Multiple Attributes:

XPath allows us to specify multiple attributes to locate elements more precisely in HTML pages.

Example:

    //tag [@attr1='val1'] [@attr2='val2'][]............etc

            []         []         []....etc

             

 

  // identify 'input' tag where class  = first class

                                                  - 2 ele found

 

 

 add name prop

 

//input[@class='firstclass'] [@name='lname'] -- 1 ele

 

add id prop also

 

 //input[@class='firstclass']  [@id='fid']           - 1 ele

 

add 3, 4... attributes and values id and name

 

 //input[@class='firstclass'] [@name='fname'] [@id='fid']   - 1 ele

                                                          []  [] []....

 

 ----------

 

Pwd:

----

<input type="password" name="pname" id="pid">

 

xpath with 'name' --> //input[@name='pname']    1 ele found

xpath with 'id' -->  //input[@id='pid']   - 1 ele

xpath with 'type' -->  //input[@type='password']           - 2  ele

 

navigate to 1st password -->   //input[@type='password'] [1]

navigate to 2nd password -->  //input[@type='password'] [2]

 

 

HW  :Write xpath for New password , Male, Female  Radio button, Electronics , Computers,  Civil,  Electrical checkboxes ?

 

HW Write xpath for login, submit, Mybutton button, link, image , cars, bikes dropdown , Multi Select dropdown ?

 

HW WAP to Click/ enter data in text boxes , password, Radio buttons, Checkboxes, link, button , images  by using relative xpath?

Handling Link

 

Handling Link:

Common Actions:

  1. Click the Link
  2. Get the URL of the Link
  3. Check if the Link is Displayed
  4. Check if the Link is Enabled
  5. Get the Text of the Link

Sample HTML:

<a href="https://www.google.com" >Click My Google</a>

 

Example Code:

package WebelementsBasics;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class LinkBasics1 {

 

            public static void main(String[] args) throws InterruptedException {

 

                        //open chrome browser

                        System.setProperty("webdriver.chrome.driver", ".\\Drivers\\chromedriver.exe");

                       

                        WebDriver  driver  = new ChromeDriver();

                        // Note: import all predefined classes and interfaces --> ctrl + shft+ o

 

 

                        // open url -file:///C:/brahma/Practise/qtp%20practise/web%20apps/ALL%20Web%20objects.html

                        driver.get("file:///C:/brahma/Practise/qtp%20practise/web%20apps/ALL%20Web%20objects.html");

 

 

                        // click 'My google' link

                        //                      1. Identify ele 2. what action to perform - click()

//                      driver.findElement(By.id(""));

//                      driver.findElement(By.name(""));

//                      driver.findElement(By.className(""));

                        // -- no name

                        // -- no id

                        //By.className("");// -- no class                   

                        Thread.sleep(3000);

                        //click 'My google'  link   By.linkText          

//                      driver.findElement(By.linkText("Click My Google")).click();

//                      driver.findElement(By.linkText("Click My Google123")).click();

 

                        // if no link text is there in page, ???

                        //  it goes to html page ,  find the ele   "by class" locator i.e link text ="Click My Google1234"

                        //   if  there is no match found in html page, it throws NoSuchElementException

 

                        //                                  Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"link text","selector":"Click My Google1234"}

 

 

                        // get url name from link -"Click My Google"

                        // href val=https://www.google.com/

                        String url = driver.findElement(By.linkText("Click My Google")).getAttribute("href");

                        //                     https://www.google.com/

 

                        // url =  https://www.google.com/

                        System.out.println("googleHrefAttr="+ url);

                        //

                       

                        //  get link text for 'click My google' link

                       

 

                        //       Linktext=

                        //  use gettext()  for  <a> text  <a>

                        //                       <p>  para-1 </p>

                        //                     <option>  Honda </option>

                        String Linktext =  driver.findElement(By.linkText("Click My Google")).getText();

                        //                             Click My Google

                        // Linktext  =  Click My Google

                        System.out.println("Linktext="+Linktext);

                        //                          Click My Google

                       

 

                        // HW  get url of   'Click My Facebook'  link

 

                        // HW Check "Click My Facebook'  link  is displayed, is enabled

 

                        // HW  Click 'Click My Facebook'   and go back to previous page , 

                       

                        //HW  get url  of 'Open Face book Link'  by using href attribute name

 

 

 

            }

 

}

 

Handling Link using PartialLinkText:

 

package WebelementsBasics;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class LinkBasics2 {

 

            public static void main(String[] args) throws InterruptedException {

                        //open chrome browser

                        System.setProperty("webdriver.chrome.driver", ".\\Drivers\\chromedriver.exe");

                        WebDriver  driver =  new ChromeDriver();

 

                        Thread.sleep(3000);

                        driver.navigate().to("file:///C:/brahma/Practise/qtp%20practise/web%20apps/ALL%20Web%20objects.html");

 

                        // clikc 'click  My google  ' link

                        //                      1. Identify ele 2. what action to perform - click()

//                                              driver.findElement(By.name(""));// -- no name

//                                              driver.findElement(By.id("")) ;// -- no id

//                                              By.className("");// -- no class

                                               

//                                  WebElement MygoogleLinkele=             driver.findElement(By.linkText("Click My Google"));//                                                     

//                                  MygoogleLinkele.click();

                       

                       

//                      By.partialLinkText("partial link text");

//                      By.partialLinkText("My Google");

//                      By.partialLinkText("Google");

 

                        // find element using by partialLinkText("My Google")

                        driver.findElement(By.partialLinkText("My Google")).click();

                                                                                   

                        // HW  if we pass invalid link text

//                                  Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"link text","selector":"Click My Google1234"}

 

                                   

                        //HW  get url name from  "click My google "link using partialLinkText()//                                        

//                                  // href val=https://www.google.com/

                                   

                                   

                        // HW  get url of   'Click My Facebook'  link using partialLinkText()

 

                        // HW Check "Click My Facebook'  link  is displayed, is enabled using partialLinkText()

 

 

            }

 

}

git commands MCQ

 Here are some multiple-choice questions (MCQs) on Git commands relevant for Selenium: 1. Which Git command is used to clone a remote reposi...