Search code examples
xpathhtmlunit

finding the current position of xpath match


I'm trying to get the current position of a xpath match. Here is a real world example

on this page http://newyork.backpage.com/homes-for-sale/

running the following xpath matches the 8th listing counting from top

//div[contains(@class, 'cat 93893742')]

I want to somehow get the ad position using xpath which at the time of posting this question is "8". I tried using prececeding-sibling::div but I am getting unexpected results.

Anyway to achieve this with xpath?


Solution

  • I'm not sure wether current version of htmlunit supports XPath 2.0, but if so you can use below expression:

    index-of(//div[starts-with(@class, "cat")], //div[@class='cat 93893742'])
    

    This will return 10 - position in common list

    If you want to get position in list for specific date (Thu. May. 11) you can try:

    index-of(//div[normalize-space()="Thu. May. 11"]/following::div[starts-with(@class, "cat")],//div[normalize-space()="Thu. May. 11"]/following::div[@class='cat 93893742'])
    

    which returns 8