Solid Static Hooks Beginner
The lowest maintenance selectors rely on attributes the UI team can
guarantee. IDs, names, and data-test values should be
your default.
Checklist
-
Reach for
By.idbeforeBy.xpath. - Use
By.namefor forms when IDs are missing. -
Create
data-testidattributes in component libraries. - Avoid brittle selectors that depend on color, font, or parent order.
CSS Power Moves Intermediate
CSS selectors are fast and readable. Combine attribute matchers, parent scopes, and pseudo classes to avoid XPath unless necessary.
| Selector | Purpose | Example |
|---|---|---|
[data-row-id^='user-'] |
Prefix match for generated IDs. |
driver.findElement(By.cssSelector("[data-row-id^='user-']"))
|
li.feed-card:has(strong) |
CSS4 :has() supported via ChromeDriver. |
driver.findElement(By.cssSelector("li.feed-card:has(strong)"))
|
section.dynamic-feed button.promote-btn |
Scope by component to avoid duplicates. |
driver.findElements(By.cssSelector("section.dynamic-feed
button.promote-btn"))
|
XPath Situations Advanced
XPath still shines when you need ancestry, order, or text functions not exposed in CSS. Keep expressions short, descriptive, and relative.
-
Never start with
//div[5]/div[2]- absolute paths break quickly. - Anchor XPath expressions with text or attributes.
- Store XPath strings in constants so refactors touch one place.
Maintenance Toolkit Expert
-
Use data URLs for experimentation: the repository
now includes
SeleniumSelectorTest, which loads a sandbox DOM so you can iterate without hitting a real environment. -
Wrap selectors in Page Objects: keep raw
Bydefinitions in one place and reuse across suites. -
Log debug info: capture
WebElement#getAttributevalues whenever a selector fails so investigation is faster.