Difference between "//" and "/" in XPath?
I tried to use XPath for python-selenium.
I used this link to test some XPaths from the tutorials:
So, I tried these two XPaths options.
-
This expression
//webengagedata//preceding-sibling::*
returned 14 results
-
And this expression
//webengagedata/preceding-sibling::*
returned 9 results
What does "//" do to get 5 more results?
source to share
/
vs //
in general
Both child
( /
) and descendant-or-self
( //
) are axes in XPath .
-
/
shortened for/child::node()/
.Use
/
to select child nodes. -
//
shortened for/descendant-or-self::node()/
.Use
//
to select a node, its children, its grandchildren, etc. recursively.
/
vs //
withpreceding-sibling::*
Your specific question brings up the difference between //preceding-sibling::*
and /preceding-sibling::*
.
Since your data is remote and complex, consider this and simpler XML instead:
<r>
<a/>
<b>
<c/>
<d/>
</b>
</r>
For this XML
-
/r/preceding-sibling::*
chooses nothing because her
has no previous siblings. -
/r//preceding-sibling::*
selects previous sibling elements of all descendants or native nodesr
. Iea
,b
,c
andd
. (Remember,/r//preceding-sibling::*
not good for/descendant-or-self::node()/preceding-sibling::*
, not/descendant-or-self::*/preceding-sibling::*
). Note that even thoughb
theyd
are no-element siblings, they are text nodes siblings because the above XML has spaces afterb
andd
. If spaces are removed, onlyb
and will be selectedd
. -
/r/descendant::*/preceding-sibling::*
selects the previous siblings of all descendant elementsr
. That isa
andc
. Note thatb
and ared
not selected because they do not precede sibling elements for any descendant elementsr
- unlike the previous example, text nodes do not match the criteria.
source to share
For your example
//webengagedata/preceding-sibling::* ---> returned 9 results
Since there are only 9 tags that are exact tag affinity webengagedata
, so it shows 9 entries
//webengagedata//preceding-sibling::* ---> returned 14 results
Here it looks at child tags and also biziclop said x/descendant-or-self::node()/y
source to share
The difference is what x//y
is shorthand for x/descendant-or-self::node()/y
.
What all.
So, while the first query selects all descendants <webengagedata>
that have another tag after them, the second only selects the preceding siblings of the tag itself.
The xpath shorthand syntax rules are explained here .
source to share