Saturday, September 14, 2013

Locating WebElements Using XPath







   In automation locating web elements in DOM is one of the important task. In DOM, if all the elements have unique ids then no problem but, if not we need to go for xpath for locating elements in DOM.

  Say for example generally we don't see any ids for the table rows & columns, in that case we need to locate table data using some other attributes. Ex: name, position, innerText.

  Below I'm writing simple example to understand the different options available in xpath. (Place mouseover the locator to see which element it will locate in table)

HTML Elements


Above html in browser

One Bike
Two Car
Three Bus
Four Jeep

Locating elements using Attributes

AttributeUsage
idBy.xpath("//table[@id='tableId']")
idBy.xpath("//td[@id='car']")
nameBy.xpath("//td[@name='Chk3']")


Locating Rows using index

RowAs a child As a sub-child
1By.xpath("//table[@id='tableId']/tbody/tr[1]")By.xpath("//table[@id='tableId']//tr[1]")
2By.xpath("//table[@id='tableId']/tbody/tr[2]")By.xpath("//table[@id='tableId']//tr[2]")
3By.xpath("//table[@id='tableId']/tbody/tr[3]")By.xpath("//table[@id='tableId']//tr[3]")
4By.xpath("//table[@id='tableId']/tbody/tr[4]")By.xpath("//table[@id='tableId']//tr[4]")

Locating Rows using functions

FunctionAs a child
position()By.xpath("//table[@id='tableId']//tr[position()=1]")
position()By.xpath("//table[@id='tableId']//tr[position()=3]")
last()By.xpath("//table[@id='tableId']//tr[last()]")
last()By.xpath("//table[@id='tableId']//tr[last()-1]")

Locating Rows using String functions

FunctionUsage
text()By.xpath("//table[@id='tableId']//tr/td[text()='One']")
contains()By.xpath("//table[@id='tableId']//tr/td[contains(text(),'hre')]")
starts-with()By.xpath("//table[@id='tableId']//tr/td[start-with(text(),'Fo')]")

Locating Columns using Xpath Axes

AxesUsage
childBy.xpath("//table[@id='tableId']//tr/child::td[text()='One']")
parentBy.xpath("//td[@id='car']/parent::tr")
preceding-siblingBy.xpath("//td[contains(@id,'bus')]/preceding-sibling::td/input")
following-siblingBy.xpath("//td[text()='Four']/following-sibling::td[@id='jeep']")
  • Child : Selects all children of the current node.
  • Parent : Selects the parent of the current node.
  • preceding-sibling:Selects all siblings before the current node.
  • following-sibling:Selects all siblings after the current node.

Happy Coding :)


Regards,
SantoshSarma



No comments:

Post a Comment

Note: Only a member of this blog may post a comment.