0

When you open a webpage in Chrome and inspect an element, when you select the element and right click again you can choose to copy the CSS selector and XPath selector. I have a project that basically needs to automatically generate the CSS selector and XPath selector based on the given HTML page, so I am wondering what kind of rules Chrome is following on generate the CSS selector and XPath.

I know Chrome generates several kinds of CSS selector. Sometimes it will use nth-child after the tag name to specify, and other times it will use class name after tag name, so which one should I choose automatically?

e.g:

html > body > div:nth-child(2) > div > div:nth-child(2) > p > a

vs

body > div.custom > div > div.master-body.col-md-10.col-sm-11.col-xs-12 > p > a.button

What’s the difference between these two and nth-child, which seems easy to break if there are other elements with a different tag inside?

dakab
  • 5,379
  • 9
  • 43
  • 67
Wu Xun
  • 1
  • 2
  • 2
    Choose neither. There are near-infinite different ways to select an element in a complex DOM document: Chrome's suggestion is only one and is created to make sure that every element has its unique selector. This is rarely desired behaviour in reality. – lonesomeday Feb 16 '17 at 18:49
  • Right, there are many ways to generate the css selector, I mean I can provide users several ways to choose, but I want to make a default one as precise as possible. Do you have any suggestions?by the way, can you answer my second question? why the nth-child seems easy to break if there are other element with different tag inside. e.g: p:nth-child(2) will get the second element

    one

    two

    but not working for

    one

    middle

    two

    – Wu Xun Feb 16 '17 at 19:00
  • This problem has been solved many times before, in various different ways. [Here's one that's supposed to be good](https://github.com/autarc/optimal-select). Personally I've never had a need for such functionality! – lonesomeday Feb 16 '17 at 19:03
  • `p:nth-child(2)` looks for elements that are both `p` and `:nth-child(2)`. There isn't one in your second example: the second `p` is the third child. `:nth-of-type` does what you mean here. – lonesomeday Feb 16 '17 at 19:05
  • Thanks, that's really helpful, one more question is when I get the css selector or xpath, sometimes it is an array, is there any way to specify the index of the array automatically – Wu Xun Feb 16 '17 at 20:02
  • Like this example: http://imgur.com/a/dSzOl – Wu Xun Feb 16 '17 at 20:10
  • Found a similar question here: http://stackoverflow.com/questions/41946684/grabbing-locator-index-automatically – Wu Xun Feb 16 '17 at 20:12
  • Possible duplicate of http://stackoverflow.com/questions/22427476/how-does-chrome-dev-tools-generate-css-selectors (which covers CSS selectors since it pertains to CSS, but the same rules apply to XPath) – BoltClock Feb 19 '17 at 18:34

0 Answers0