Xpath: find table cell with same position in another row

I am analyzing a web page that includes this structure:

<tr> <td>Label 1</td> <td>Label 2</td> <td>Label 3</td> <td>Something else</td> <\tr> <tr> <td>Item 1</td> <td>Item 2</td> <td>Item 3</td> <\tr> 

What I need to do is select an element based on its label, so I think that if the label is in the third tag on this line, I can grab the third tag on the next line to find the element. I cannot find a way to use the position () function this way, and maybe xpath (1.0) will not be able to handle this type of filtering.

My best attempt: //td[ancestor::tr[1]/preceding-sibling::tr[1]/td[position()]] . I was hoping the position () function would capture the <td> position at the beginning of the xpath, since the rest of the xpath is a filter for this node.

Am I trying to make it even possible?

+7
html xpath selenium-webdriver
source share
1 answer

You're on the right track - yes, you can use position() along with count() .

To select the Item 2 text specified by Label 2 :

 //td[. = 'Label 2']/../following-sibling::tr/td[position() = count(//td[. = 'Label 2']/preceding-sibling::td)+1]/text() 

Explanation: Select cell nth , where n is specified by the number of neighbor cells that exist before the cell that has the desired label in the previous row. In fact, use the count() function to determine the position in the label line, and then select the corresponding cell in the next line down, matching it with position() .

+6
source share

All Articles