Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the preceding element?

Tags:

xpath

<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 
like image 517
Pablo Avatar asked Mar 25 '12 03:03

Pablo


People also ask

How do you write preceding in XPath?

Preceding Axis: Now we will select all nodes by using the preceding axis in the document that comes before the current node. XPath: //input[@id = 'u_0_2']//preceding::input (1 of 4 matched). The above expression identified all the input elements before “login” button using the preceding axis.

What is preceding and following in XPath?

The following-sibling and preceding-sibling axes contain the siblings before or after the context node, and the following and preceding axes contain all nodes in the document before or after the context node, but: None of these axes contain attribute or namespace nodes.

What is the difference between preceding and preceding sibling?

In this diagram, the preceding:: nodes are circled, and the more specific preceding-sibling:: nodes are given a red border. The preceding-siblings are nodes that share the same parent node, and come before the current node in the document. The preceding:: node is any node that comes before the element in the document.


2 Answers

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() ------------------+------+------------------ 
like image 166
kev Avatar answered Sep 21 '22 23:09

kev


//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

like image 32
Jainish Kapadia Avatar answered Sep 19 '22 23:09

Jainish Kapadia