Saturday, 30 March 2019

How to write xPath


There are Two Types of Xpath
1)Absolute Xpath
2)Relative Xpath
1)Absolute Xpath:
a) It is a direct way to locate the Element.
b) It start with Single Element(/)which means it try to search the Element from the Root.
Example:
/html/body/equote-root/equote-risk/div/div/div[1]/equote-area-sorter/div/equote-panel/div/div[2]/div/div[2]/button
2)Relative Xpath:
a) It starts from the Middle of the HTML.
b) Starts with double slash (//)which means it try to search the Element anywhere in the DOM.
c)It is flexible compare to Absolute Xpath.
Example:
//span[contains(text(),'Submit Button')]


 How to Write a Smart XPaths for Complex and Dynamic Elements

1)Use Contains:
When a Element is Dynamic it is easy to find the Elements.
Example:
//*[contains(@name,'userName')]
//*[contains(@href,'mercurywelcome.php?osCsid=eb1d150686047b0beb894f5ec0313408')]
//*[contains(@text,'here')]




2)Use OR & AND

Using OR when both the condition is true it find the Element, when there is one condition is true another one is false in that time also it find the Element.
Example:
//*[@name='pass' or @name='login']


Using AND when both the condition is true it find the element otherwise it fails to find the element.

//*[@name='password' or @name='login']



3)Starts-with
Match with starting text of the attribute is used to find the element whose changes dynamically.
Example:
//input[starts-with(@name,'principal')]



4)Text

Find the element with the exact text match.
Example:
//a[text()='REGISTER']



Xpath Axes Method:

a) Following
b) Ancestor
C) Child
d) Preceding
e) Following-sibling
f) Parent
g) Self
h) Descendant

a) Following:

To select all the elements from the node.
Example:
//*[@type='text']//following::input
With the input[1] it find the particular element.
//*[@type='text']//following::input[1]




b) Ancestor
First It finds the text which is ‘Enterprise Testing’
Then start to find the elements in node.
Example:
//*[text()='Enterprise Testing']//ancestor::div

c) Child
It select all the children elements from the node.
Example:
//*[@name='country']/child::option
//*[@name='country']/child::option[150]


d)Preceding

It selects all the node come before the current node.
Example:
//*[@type='image']//preceding::input
//*[@type='image']//preceding::input[10]








e) Sibling:
It selects the following sibling of the context node.

Example:
//*[@type='text']//following-sibling::input
//*[@type='text']//following-sibling::input[1]

f) Parent
It selects the parent of the current node
Example:
//*[@id='rt-feature']//parent::div
//*[@id='rt-feature']//parent::div[1]

g) Self
It select the current node.
Example:
//*[@type='password']//self::input
//*[@type='password']//self::input[1]


h)Descendant
Example:        
//*[@id='test']//descendant::a


No comments:

Post a Comment