Jose Soto
Jose Soto

Reputation: 25

XPath for HTML table element using headers

I have a simple table like this one:

          <table>
              <tbody><tr>
                <th> Name1 </th>
                <td>
                  A
                </td>
              </tr>
              <tr>
                <th>Name2</th>
                <td>
                  B
                </td>
              </tr>
            </tbody></table>

I need the XPath to the value B, which I can do with:

//table/tbody/tr[2]/td[1]

However this relies on the position of the row (the number 2), which may change from one example to another. I would like to get the XPath of element B but using the header name (Name2) instead of the position.

Any idea of how to get it?

Upvotes: 1

Views: 225

Answers (1)

kjhughes
kjhughes

Reputation: 111736

This XPath,

//th[normalize-space()='Name2']/following-sibling::td

well select the first td element following each th element whose normalized string value is 'Name2'. (By testing the normalized string value of td, any leading and trailing whitespace will be ignored. contains() has the problem that it will also match, for example, 'Name20'.)

See also

Upvotes: 1

Related Questions