What are the differences between absolute and relative XPath?

221    Asked by CharlesParr in QA Testing , Asked on Jan 2, 2024

I am a QA engineer and I am testing a web application in which I need to locate elements on the page for automation. However, I am still determining the differences between absolute and relative XPath as I need to locate elements. How can I decide which one I should utilize? 

Answered by Chloe Burgess

 In the context of selenium automation, the difference between absolute and relative xpath lies in their specificity and flexibility:-

Absolute Xpath:

It is mainly used in specifying the complete path from the root component to the targeted component in the HTML DOM hierarchy. Here is the example given:-

    Element = driver.find_element_by_xpath(‘/html/body/div/div[2]/form/input[1]’)

It Is less recommended in your scenario as its specificity to the current structure

Relative Xpath:

It is also used in defining the elements or components however this finds the elements based on their relationship with other elements rather than relying on the whole structure of DOM. Here is the example given:-

    Element = driver.find_element_by_xpath(‘//input[@id=”username”]’)

  It offers more flexibility and it is less brittle in terms of changes. Therefore you can choose relative Xpath to use for your provided particular scenario.


Your Answer

Interviews

Parent Categories