1

For a HTML page like this I'm writing two xpath statements to fetch the text from a td element. First xpath is to get the position of the th element that matches my requirement.

count(.//th[contains(., 'Header5')]/preceding-sibling::*)+1

Then I put the count value returned from the above to this xpath and get the text

.//tr[2]/td[**count**]

How can I merge these two xpaths in to single xpath and get the result. I tried something like this but it always selects the first td

.//tr[2]/td[count(.//th[contains(., 'Header5')]/preceding-sibling::*)+1]
(.//tr[2]/td)[count(.//th[contains(., 'Header5')]/preceding-sibling::*)+1]

Here is the html structure

<thead>
    <th> Header1 </th>
    <th> Header2 </th>
    <th> Header3 </th>
    <th> Header4 </th>
    <th> Header5 </th>
    <th> Header6 </th>
</thead>
<tbody>
    <tr>
    <tr>
        <td> Cell1 </td>
        <td> Cell2 </td>
        <td> Cell3 </td>
        <td> Cell4 </td>
        <td> Cell5 </td>
        <td> Cell6 </td>
    </tr>
</tbody>

1 Answer 1

1

This one should do the trick:

.//tr[2]/td[count(//th[contains(., 'Header5')]/preceding-sibling::th) + 1]

Note that /td[count(.//th)] means count of th nodes that are descendants of td while /td[count(//th)] means count of th wherever in DOM, so be careful with the context node (the dot)

Sign up to request clarification or add additional context in comments.

1 Comment

yeah, now i understood why my code didn't work. thanks for clarifying.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.