This is a follow-up to What makes a good selenium locator?
Motivation
I've been thinking about detecting the complexity of CSS selectors statically.
The scope I'm working in is both test-automation and web-scraping where choosing a reliable CSS selector is important to be as less dependent on UI/markup/layout changes as possible.
Currently, I'm able to check the "depth" of a CSS selector by parsing it via css-selector-parser
and simply counting the number of nodes. If the number of nodes is more than 5 I'm concluding that this is a potentially complex CSS selector. The reasoning behind this is that, the more nodes a selector has in the path, the more dependent on the HTML structure of the page it is - the more fragile it is. For instance, this CSS selector would be considered "fragile" (6 nodes):
.content > table > tbody > tr:nth-child(2) > td.cell > input#email
Eventually, I'm thinking to develop a metric where each selector would get a special "score" value that would a measurement of a selector being more solid/durable. Inspired by famous code complexity metrics, like Cyclomatic Complexity or Maintainability Index.
Question
What parameters would you consider to determine if a CSS selector is resistant to a change? What makes a reliable CSS locator?
Thoughts
- usage of layout-oriented
bootstrap
classes inside CSS selectors would be a signal of a bad locator - implementation-specific classes and attributes would make a selector less reliable. (e.g. in case of AngularJS -
ng-scope
orng-binding
classes) - using
id
orname
attributes would probably be desirable