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
Attribute | Usage |
---|---|
id | By.xpath("//table[@id='tableId']") |
id | By.xpath("//td[@id='car']") |
name | By.xpath("//td[@name='Chk3']") |
Locating Rows using index
Row | As a child | As a sub-child |
---|---|---|
1 | By.xpath("//table[@id='tableId']/tbody/tr[1]") | By.xpath("//table[@id='tableId']//tr[1]") |
2 | By.xpath("//table[@id='tableId']/tbody/tr[2]") | By.xpath("//table[@id='tableId']//tr[2]") |
3 | By.xpath("//table[@id='tableId']/tbody/tr[3]") | By.xpath("//table[@id='tableId']//tr[3]") |
4 | By.xpath("//table[@id='tableId']/tbody/tr[4]") | By.xpath("//table[@id='tableId']//tr[4]") |
Locating Rows using functions
Function | As 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
Function | Usage |
---|---|
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
Axes | Usage |
---|---|
child | By.xpath("//table[@id='tableId']//tr/child::td[text()='One']") |
parent | By.xpath("//td[@id='car']/parent::tr") |
preceding-sibling | By.xpath("//td[contains(@id,'bus')]/preceding-sibling::td/input") |
following-sibling | By.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
Regards,
SantoshSarma
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.