Xpath method to get col number

Viewed 20

I want to access the data from a column in multiple rows. This column is dynamic but always has the same header. Sometimes it's td[5] sometimes it's td[20] depending on how many months the user wants to display. Currently I use a for loop to find that column number.

let col = 4

while(getText(//thead//th[col]) != "YTD"){
   col++
}

Then when I need that same column in subsequent rows, I can access //tr[12]/td[col].

Is there a better way? The structure is a pretty standard

<table>
  <thead>
    <tr>
      <th></th>
      ...
      <th>YTD</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td></td>
      ...
      <td></td>
    </tr>
  </tbody>
</table>
1 Answers

The preceding-sibling axis is what you need here.

Find the header, and count the number of preceding-sibling <th> elements.

count(//thead//th[col="YTD"]/preceding-sibling::th) + 1
Related