🎯 Locators with By

Locators with By: A By locator is the address description you hand a courier, and the TYPE of description decides the delivery's fate: By.id is like a national ID number — unique

A By locator is the address description you hand a courier, and the TYPE of description decides the delivery's fate: By.id is like a national ID number — unique and direct on the page, it finds the door on the first try; By.cssSelector is "neighborhood + street + building" — flexible, but confused if the street is renamed; By.xpath is "turn left at the third building, next to the red door" — it can describe ANY place but is the most fragile: when a new building rises in the neighborhood (a new div lands in the DOM), it knocks on the wrong door. If By.xpath can find any element, why doesn't everyone just use it — wouldn't one tool be enough? No, because power and fragility sit on the same axis: position-based XPath (div[3]/span[2]) breaks at the smallest structural DOM change, and locator maintenance is the biggest line item in UI automation cost. Java comparison: By is an abstract factory — By.id("x") returns a ById object; just like choosing ArrayList/LinkedList behind the List interface, all implement the same contract (telling findElement "how to search for me") but with different performance/fragility profiles. The real QA cost: flaky locators push the team into a "tests are red again, ignore them" culture — once trust in the suite is gone, the entire automation investment is wasted. The locator priority (id > name > css > xpath) is therefore not a style preference but a maintenance-cost strategy.

🧭 The 8 By Strategies: One by One

Micro Lab: Locator strategy practice

Replace the TODO line with the critical line from the expected solution. This is not a real runtime; the goal is to reinforce writing the correct structure in a controlled way.

By Strategy Priority: Try Them in the Right Order

If it exists, ALWAYS the first choice: By.id is the most reliable strategy, expected to be unique on the page.

Common on form fields (input, select) — the second choice when no id exists.

Is there a meaningful class?

By.cssSelector: can search by attribute, hierarchy, and state — the default choice when no id exists.

If none work: By.xpath

The most powerful strategy — can search by text and navigate axes — but also the most fragile.

Avoid position-based XPath

Absolute paths like /html/body/div[3] break at the smallest DOM change — prefer text/attribute-based XPath when possible.

Think in LEGO: the Locator Priority Ladder