Tuesday, April 5, 2011

Using XPath: find link in cell 3 rows up

Hi Guys!

I have multiple rows in a table, in one of which is a link I'd like to automatically click. For my starting point I have the last instance that a row contains the text "Test Question?":

ID: 1416

Edit/Approve Ignore Email Name: Submitter Name

Open N/A Location: Submitter Location

Member: No

Question Text: Test Question? Response 1 Text:

Response 2 Text:

ID: 1417

Edit/Approve Ignore Email Name: Submitter Name

Open N/A Location: Submitter Location

Member: No

Question Text: Test Question? Response 1 Text:

Response 2 Text:

So, //tr[td='Test Question?'][last()] would be something like "Question Text: Test Question?"

Anyway, three rows up from that there's a row with a bunch of links in it. I would like the xpath to the link in the first cell.

Now I tried to use position(), but stuff like //tr[position()=(//tr[td='Test Question?'][last()][position()])-3] just isn't the right way to do it and I can't find any good examples.

Thanx

Dave

From stackoverflow
  • That's going to be a pretty gnarly xpath to say the least, but you're looking at axes starting with ancestor::tr and then preceding-sibling. Tunnel up to <tr>, then across three (you'll need to ref position() here I think) and then down in a normal fashion from there to your goal.


    Edit: easier than I thought, preceding-sibling counts backwards.

    ./ancestor::tr/preceding-sibling::tr[3]/td[1]/a
    
    Dave Babbitt : So, if //ancestor::tr[td='Test Question?'][last()]/preceding-sibling::tr[3]/td[1]/a gets me all the "Test Question?" links, how do I get the last one?
    Dave Babbitt : (When I use XPather, //ancestor::tr[td='Test Question?'][last()]/preceding-sibling::tr[3]/td[1]/a gets me the same thing as //ancestor::tr[td='Test Question?']/preceding-sibling::tr[3]/td[1]/a so you've possibly answered the question and I'm just having trouble on my end trying to verify it.)
    annakata : I thought you had the starting node already? Nonetheless, you're making it over complicated for yourself. Detach the problem of finding the seed, and prefix to the above. Try this instead: //td[self::td='Test Question?']/ancestor::tr/preceding-sibling::tr[3]/td[1]/a
    Dave Babbitt : Yes, //ancestor::tr[td='Test Question?'][last()]/preceding-sibling::tr[3]/td[1]/a works. Thanx

0 comments:

Post a Comment