P A N
P A N

Reputation: 5922

xPath: From parent node, descend to sub-sub-sub child node that matches condition?

I'm trying to write a xpath that gets the text from "I want to get this text snippet" below.

<root>
  <div class="box">
    <div class="col-lg-12">
      <h2>Issuer</h2>
    </div>
  </div>
  <div class="table-responsive">
    <table class="table">
      <tbody>
        <tr>
          <td> Name </td>
          <td class="text-right"> I want to get this text snippet </td>
        </tr>
      </tbody>
    </table>
  </div>
</root>

So far I have this:

//h2["Issuer"]/parent::div/parent::div/following-sibling::div//td["Name"]/following-sibling::td/text()

There are two parts to this line at the moment:

  1. //h2["Issuer"]/parent::div/parent::div/following-sibling::div which takes us to <div class="table-responsive">.
  2. //td["Name"]/following-sibling::td/text() which takes us to the text snippet target in its <td> block.

Both parts are important because there are multiple places in the real webpage source code where <td> Name </td> can be found. So the first part determines where in the overall structure to start looking.

Is my usage of // leading the second part the correct way to descend to any child node that matches the condition? I ask this because I can't find a match.

Upvotes: 2

Views: 145

Answers (1)

alecxe
alecxe

Reputation: 473853

You are almost correct, just add a text check:

//td[normalize-space(.) = "Name"]/following-sibling::td[1]/text()

Upvotes: 2

Related Questions