There are a lot of guidelines that will help you in choosing good, reliable, reusable, maintainable selectors. Simply inspecting an element and copying its xpath is one of the worst approaches.
When selecting an element:
- Don't overspecify thus 'hard-coding' to the current layout and presentation
- Don't underspecify wuth selectors that aren't unique or specific enough
- Do use css ID fields
- Don't use ID's that are used for data ID's
- Prefer avoiding using layout tags such as
table
,tr
, td
- Prefer avoiding style tags such as
b
, i
- Consider using data-element attributes, e.g.
data-last-name
, data-first-name
e.g.
NOT-SO-GOOD
body table tr tr td td td span span table tr td td td div # Way Too specific
(this is what browser examine xpath might give you)
body table tr tr td td td # Still too specific
span # Too unspecific
div[@id=942] # Uses data id
div span b a#first_auto # Uses layout
BETTER
.autos #auto li
.insurance_company li[data-primary-vehicle]
.vehicle .model div.primary
In addition to the benefits listed above you can also see that using the 'BETTER' selectors would lead to more human-readable tests as the selectors used are very descriptive of the data they are manipulating.
The tools you should use are the various built-in or add-on DOM inspection tools (like firebug for firefox for example) that let you look at the source. The most important step is you figuring out what parts of the path you see and how to use them.
For trouble-shooting, use the console to try and select parts of the path. For example if the path is .autos #auto li
you can try using the console to select .autos
and then .autos #auto
and then .autos #auto li
to see which are valid/invalid.