2

In google chrome, you can get the xpath of an element via if you right click on an element -> copy xpath:

Here is how GIF

QUESTION: Is it possible to dynamically access an xpath generated by Chrome using some Chrome Api (?) / Functions. I want to be able to copy the xpath in code?

Any ideas please?

Or if you know a better way to locate a dom element (i.e. a reference that can be persisted so I can locate it 'later' e.g. on another server)?

Shaz
  • 1,443
  • 1
  • 27
  • 67
  • 1
    Why? Computer-generated XPath is next to useless. – Tomalak Dec 13 '20 at 09:10
  • Please explain? I'm wondering if there is a chrome api function where you can pass in dom element (id?) and returns the xpath. Similar to what a user can do on chrome GUI - hope that makes sense? I need a way to locate a dom element and persist it (as a reference - even though i know it can be changed / is fragile..) – Shaz Dec 13 '20 at 09:14
  • Please let me know if you know a better way to locate a dom element (i.e. a reference that can be persisted so I can locate it 'later' e.g. on another server) – Shaz Dec 13 '20 at 09:16
  • https://stackoverflow.com/questions/2661818/javascript-get-xpath-of-a-node see answer number 2 – JustRaman Dec 13 '20 at 09:16
  • I have seen this answer, been testing this function - unfortunately it breaks on edge cases - e.g. returns empty class name sometimes i.e. /div[@class=""] - Really hard to do this reliably! – Shaz Dec 13 '20 at 09:19
  • 1
    I know what you mean, but the *result* of automatic XPath generation is useless. XPath is meant to be written by hand. Automatically generated XPath is too complicated and much too specific, and even small changes in the DOM structure, like they happen all the time in today's dynamic pages, will cause those XPaths to break. In other words, they are not stable enough to be useful. – Tomalak Dec 13 '20 at 09:24
  • Is there a better alternative to xpath - perhaps? – Shaz Dec 13 '20 at 09:25
  • @Tomalak is right: XPath is not the problem. Your expectation that there is a single answer to the question of how to locate an unidentified node in a document is the problem. Without specifying a fixed framework or a fixed set of invariants, your question is under-constrained and autogenerated XPath's have to be over-constrained. – kjhughes Dec 13 '20 at 19:21

0 Answers0