What are the differences between absolute and relative XPath?
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?
In the context of selenium automation, the difference between absolute and relative xpath lies in their specificity and flexibility:-
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.