For Selenium beginners, the below listed XPath examples are really helpful to write a relative XPath instead of messing up with an absolute one.
1) Select First & Last Node
- Selecting first hyper link in a page:xpath=/descendant::a
- Selecting first link using Position method:xpath=/descendant::a[position()=1]
- Selecting last link:xpath=/descendant::a[last()]
- Selecting first link which has innerText as ‘English’:xpath=/descendant::a[text()=’English’]
- Selecting first input tag which has ‘class’ attribute:xpath=/descendant::input[@class]
2) Selecting a node using multiple condition
- Selects input tag using ‘type’ and ‘class’ attributes value:xpath=//input[@type=’text’ and @class=’gbqfif’]
- Selects a button which has name and class attributes: xpath=//button[@name and @class]
3) Getting parent node from child node
- Gets the input tag’s parent node using ‘..’ : xpath= //input[@name=’q’]/..
4) Selecting parent node from child node
- Selects the ‘DIV’ which is having ‘INPUT’ tag: xpath=//div[input]