Chrome Extension: Programmatically inspect element and “copy xpath” or “copy css path” [closed]

六眼飞鱼酱① 提交于 2020-01-03 06:03:21

问题


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.


回答1:


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 :))



来源:https://stackoverflow.com/questions/24834109/chrome-extension-programmatically-inspect-element-and-copy-xpath-or-copy-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!