Checkout our demo site to practice selenium https://magento.softwaretestingboard.com/

0 like 0 dislike
175 views
by The go-to Tester (324 points)
Tell me... How are absolute XPaths different from relative XPaths?

 And one more thing... Why are relative XPaths typically preferred over absolute XPaths in automated tests?

Please explain both questions with examples

Thank You...!!

1 Answer

0 like 0 dislike
by The go-to Tester (181 points)
selected by
 
Best answer

Absolute xPath: Absolute xPath is complete path to the element, starting from the HTML tag. Absolute path starts with single slash "/".

Relative xPath: Relative xPath is relative path to the element. It starts with the best uniquly identified parent. Relative path starts with double slash "//".

Example you have an element as given below.

<html>

<body>

<div class="some-class"> <p> hello world <p></div>

<body>

</html>

In above example, Absolute xPath can be

/html/body/div/p

and relative xPath can be

//div[class="some-class"]/p

Relative xPaths are short and are more reliable. With the time, application tend to change. New functionalites will be added or removed. While doing so, element position may change on the webpage. Absolute xPaths are changed more often then relative xPath.

Eg.

In above example, you have happen to add one more element above existing div.

<html>

<body>

<div class="clear"></div>

<div class="some-class"> <p> hello world <p></div>

<body>

</html>

In above example, Absolute xPath will be

/html/body/div[2]/p

and relative xPath can be

//div[class="some-class"]/p

Lets try one more example by adding a parent element.

<html>

<body>

<div>

<div class="some-class"> <p> hello world <p></div>

</div>

<body>

</html>

In above example, Absolute xPath will be

/html/body/div/div/p

and relative xPath can be

//div[class="some-class"]/p

So, as you observed, relative xpath did not change.

 
Hope that helps!


This site is for software testing professionals, where you can ask all your questions and get answers from 1300+ masters of the profession. Click here to submit yours now!

...