How to get the preceding element?
33,182
Solution 1
You can use this xpath
:
//a[.="Next."]/preceding::a[1]
If I were to diagram it out, using an X
to represent the current location, it would look like this:
------------------+------+------------------
preceding-sibling | self | following-sibling
------------------|------|------------------
last() ... 2 1 | X | 1 2 ... last()
------------------+------+------------------
Solution 2
//a[contains(text(), 'Next.')]/preceding::a[contains(text(), '171')]
Explanation of xpath: Using text
method along with <a>
tag and then move ahead with preceding
keyword to locate the element 171
Solution 3
I know this is old and if you didn't know the containing element preceding the "Name." element this wouldn't be a solution for you. BUT, if you were wanting to find exactly that element and there are several "171" elements all over the page. The way to distinguish it from the rest, you could use the following.
//p[b[contains(., 'Next.')]]//a[contains(., '171')]
Author by
Pablo
Updated on July 12, 2020Comments
-
Pablo almost 4 years
<p class="small" style="margin: 16px 4px 8px;"> <b> <a class="menu-root" href="#pg-jump">Pages</a> : <b>1</b> , <a class="pg" href="viewforum.php?f=941&start=50">2</a> , <a class="pg" href="viewforum.php?f=941&start=100">3</a> ... <a class="pg" href="viewforum.php?f=941&start=8400">169</a> , <a class="pg" href="viewforum.php?f=941&start=8450">170</a> , <a class="pg" href="viewforum.php?f=941&start=8500">171</a> <a class="pg" href="viewforum.php?f=941&start=50">Next.</a> </b> </p>
I want to catch
a
element containing 171. So basically the preceding element from the Next.//a[.='Next.']//Not sure how to use preceding here