LU Cai
LU Cai

Reputation: 514

xpath - axes methods return wrong nodes

I have noticed that using xpath axes methods sometimes return wrong nodes. I have two examples:

url: "http://demo.guru99.com/v1/"

<tr>
   <td align="center">
      <img src="../images/1.gif">
      <img src="../images/3.gif">
      <img src="../images/2.gif">
   </td>
</tr>

I can select three img elements by axes methods "//td//child::img". However when I use "//td//following-sibling::img", it can still return the second and third img elements. As far as I know, child and sibling are two different thing, so why this happens?

url: http://demo.guru99.com/selenium/guru99home/

<div class="rt-grid-12 rt-alpha rt-omega" id="rt-feature">
  <div class="rt-grid-6 ">
    <div class="rt-block">
        <h3>
            Desktop, mobile, and tablet access</h3>
        <ul>
            <li>
                <p>
                    Free android App</p>
            </li>
            <li>
                <p>
                    Download any tutorial for free</p>
            </li>
            <li>
                <p>
                    Watch video tutorials from anywhere&nbsp;</p>
            </li>
        </ul>
        <p>
            <a href="https:/play.google.com/store/apps/details?id=com.vector.guru99&amp;hl=en"><img alt="" src="images/app_google_play(1).png"></a></p>
    </div>
  </div>
  <div class="rt-grid-5 ">
    <div class="rt-block">
        <img src="images/logo_respnsivsite.png"><br>
    </div>      
  </div>    
</div>

Here, if I use "//div[@id='rt-feature' and (@class='rt-grid-12 rt-alpha rt-omega')]//following-sibling::div", those div elements which should be child elements are still be counted as siblings

Use "//div[@id='rt-feature' and (@class='rt-grid-12 rt-alpha rt-omega')]//parent::div", the self element and its child div elements are all counted as parent.

This cause me a lot of confusion, please help me.

Upvotes: 0

Views: 142

Answers (1)

Michael Kay
Michael Kay

Reputation: 163575

Suggesting that the XPath parser returns the wrong nodes, rather than that you don't understand why it is returning what it does, is starting from the wrong mindset. Unless you know the XPath parser is unreliable, start with the assumption that it is right and your expectations are wrong. Then go to the spec and study the semantics of the expression you have written.

You will find that

//td//following-sibling::img

is an abbreviation for

/descendant-or-self::node()/td/descendant-or-self::node()/following-sibling::img

so you have asked for all the following siblings of all the descendants of all the td nodes, which is exactly what you are getting.

I've come across people who habitually write "//" in place of "/" as a sort of magic fairy dust without having the faintest idea what it means. Don't do it: read the spec.

Upvotes: 1

Related Questions