3

I want to know if it's possible to programmatically access an element, say the current element I am hovering over, and perform the equivalent of right clicking it, going to "inspect element", selecting it in the Elements tab, right click "copy xpath" or "copy css path".

Additionally, I would like to know if it's possible to get xpath or css path of similar elements. Say all the links on the side of this website, how to make chrome get an xpath or css path expression that represents that group of links under Similar Questions?

My purpose is to write an extension that lets me easily grab xpath or css path of elements on page that is accurate enough for automating web applications for testing.

user299709
  • 4,922
  • 10
  • 56
  • 88

1 Answers1

3

One possibility is to use

document.querySelectorAll(":hover");

Which will return a NodeList of elements in deciding order from parent => child => ... => last child. So the last element in the NodeList will be most "specific", and it would (most of the time) be possible to construct a css path to that specific element by working backwards through the NodeList.

For your second question, you are veering into extremely difficult territory! In general, if you are trying to extract information from an unknown html page it is simply not feasible to do so automatically/programmatically without knowing the page structure before hand.

If you want your extension to only extract paths from a certain (small) number of sites then great...you can (manually) see if the sites have well structured markup and hard code those paths into your code. Otherwise, for any general site, finding similar paths should be left as an exercise to the user (perhaps using the hover method as mentioned above :))

berrberr
  • 1,914
  • 11
  • 16
  • I guess there's no other way eh. it would be nice if I could know how "Copy Xpath" really works underneath. Wouldn't it be great if you could take do `copyXpath(document.querySelectorAll(":hover");` – user299709 Jul 19 '14 at 05:59
  • 1
    @user299709 You can create your own copyXpath like [stijn de ryck](http://stackoverflow.com/a/5178132/1816580) did. – Artjom B. Jul 19 '14 at 09:23
  • similar to the copyXpath function mentioned in the comment above, is there a programmatic wayfor getting the CSS selector of an element? – Deven Jan 03 '18 at 12:36