2

I have two xpath selectors that find exactly the same element, but I wonder which one is better from code, speed of execution, readability points of view etc.

First Xpath :

//*[@id="some_id"]/table/tbody/tr[td[contains(., "Stuff_01")]]//ancestor-or-self::td/input[@value="Stuff_02"]

Second Xpath:

//tr[td[@title="Stuff_01"]]//ancestor-or-self::td/input[@value="Stuff_02"]

The argument for example is that if the code of the page will be changed and for example some "tbody" will be moved that the first one won't work, is it true ? So any way which variant of the code is better and why ?

I would appreciate an elaborate answer, because this is crucial to the workflow.

9
  • maybe the answers to this my old question will be helpful! stackoverflow.com/questions/34092985/…
    – fabdurso
    Commented Dec 14, 2015 at 10:55
  • Partly it does, thx, but not all of it...
    – Newcomer
    Commented Dec 14, 2015 at 10:58
  • I will add it as an answer to help other users too
    – fabdurso
    Commented Dec 14, 2015 at 11:29
  • 2
    1 If this is crucial as you say, you should take the time to include a reduced example of the targeted HTML and a description of exactly what you're trying to select, because it is possible that neither XPath is ideal. 2 Performance is unlikely to matter; measure first. 3 ...especially if you use an @id or other anchor point to hone in on a reduced subtree before further restraining the selection space.
    – kjhughes
    Commented Dec 14, 2015 at 13:04
  • 1
    Please show a minimal, complete and verifiable sample of your HTML document. Otherwise, nobody can tell you more than @kjhughes already did. The usefulness of XPath expressions depends highly on the document you apply them to. (And to emphasize this again, we also need to know what you are looking for.) Commented Dec 14, 2015 at 19:32

1 Answer 1

2

It is possible that neither XPath is ideal. Seeing the targeted HTML and a description of the selection goal would be needed to decide or to offer another alternative.

Also, as with all performance matters, measure first.

That said, performance is unlikely to matter, especially if you use an @id or other anchor point to hone in on a reduced subtree before further restraining the selection space.

For example, if there's only one elem with id of 1234 in the document, by using //elem[@id="1234"]/rest-of-xpath, you've eliminated the rest of the document as a performance/readability/robustness concern. As long as the subtree below elem is relatively tame (and it usually will be), you'll be fine regarding those concerns.

Also, yes, table//td is a fine way to abstract over whether tbody is present or not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.