What is xpath in Selenium with python?

Selenium Web DriverAutomation TestingSoftware Testing

Xpath is one the locators used in Selenium to identify elements uniquely on a web page. It traverses the DOM to reach the desired element having a particular attribute with/without tagname.

The xpath can represented by the ways listed below −

  • //tagname[@attribute='value']

  • //*[@attribute='value']

The xpath can be created by the following methods −

  • OR & AND expression.

  • following- sibling expression.

  • parent.

  • child.

  • ancestor.

  • self.

  • descendant.

  • starts-with()

  • ends-with()

  • text()

  • preceding.

There are two types of xpath – absolute and relative.

Relative xpath – This path begins from any part of the DOM html. It is represented by double slash // and helps to identify elements from any part of the web page and the xpath expression is not a lengthy one.

It is always better to use relative xpath since we need not start from the root to locate our element. So in case any attributes or their values are getting modified, the probability of getting affected to an incorrect xpath is less.

Syntax

driver. find_element_by_xpath("//input[@class='gsc-input']")

Absolute xpath – This path starts from the root html to the desired element. It is represented by single slash /. It is lengthier compared to relative xpath and if any of the attributes or their values starting from the root element get changed, then we end up not being able to uniquely identify our desired object on the page.

Syntax

driver. find_element_by_xpath("/html/body/div/input")

Xpath can perform bidirectional flow which means the traversal can be both ways from parent to child and vice- versa.

Parent to child

Syntax

driver.find_element_by_xpath("//table/tbody/tr[2]/td[2]")

Child to parent

Syntax

driver. find_element_by_xpath("//input[@id='job']/parent::div")

In terms of speed, xpath is slower compared to css.

raja
Published on 29-Jul-2020 11:09:21
Advertisements