Xpath
Xpath ~30 mins

What is Xpath? (20 min)

XML path –address of the element in DOM.
When to use?
Basic locators are not available / changing dynamically.
How to write xpath?
Based on the element path and syntax

Two Types of Xpath:
Absoulte Xpath
Relative Xpath

1. Absolute Xpath:

• long path
• Starts from root tag() and ends at the target element tag.
• Starts with “/ “ and traverse through each and every tag in hierarchy to reach the required WebElement.

The syntax for the absolute xpath is

    /html/body/div[2]/div/div/form/p/input

2. Relative XPath

• works in relation with the WebElement location in the DOM.
It goes directly to the address of the target WebElement.

• Relative XPath starts with the “//” which locates the inner or middle part of the DOM.

General syntax of the Relative xpath is:

     //tagname[@attribute='attributeValue’] 

Types of Relative Locators Relative Locators

➢ Basic XPath
➢ Advanced XPath

Basic Xpath (5 Types)– Attribute Based

1.Attribute Based XPath: ->uses the attribute and attribute value of the WebElement in the DOM.

Syntax:

 //tagName[@attribute='attributeValue’] 

Example

 //input[@id=‘username’

Basic Xpath – Text Based

2. Text Based Xpath:

->based on the text displayed for the WebElement in dom
Syntax:

 //tagName[text()='text value in DOM'] 

Example:

 //a[text()='Create New Account']

Basic Xpath – Partial Match

3. Partial attribute Based Xpath:

• uses the partial attribute value of the WebElement
• Contains ->check for the given attribute value with the value in DOM

Syntax:

 //tagName[contains(@attribute, 'Partial value of the attribute')] 

Example:

 //input[contains(@id,’user’)]

Basic Xpath – Partial Match

4.Partial Text Based Xpath: ->uses the partial text value of the WebElement

Syntax:
//tagname[contains(text(),' Partial text in my DOM' ')]
Example:

    //a[contains(text(),’Create’)]

Basic Xpath – Collection

5. Collection Based Xpath:

• when there is multiple matches of found for a xpath
• uses index to match the exact element
• Index starts with 1

Syntax:

 (//tagName[@attribute='attributeValue'])[index]

Example

   (//input[@class='inputLogin'])[2]