4. Locators & stability patterns
Selenium WebDriver · 48 pages source format
Stable locators and stable tests. Page Factory optional — clarity over magic. data-testid agreements with dev.
What you'll learn
- Locator priority
- Stale element handling
- Iframe and window switches
Locator priority doc
ID → data-testid → CSS → XPath last. Document in SELECTORS.md.
Do this now
Refactor 3 XPath locators to CSS or ID on the-internet pages.
StaleElementReferenceException
DOM refreshed after AJAX — re-find element instead of reusing reference.
Do this now
Reproduce on dynamic content page. Fix by re-locating inside wait.
Frames and windows
driver.switch_to.frame() and switch_to.window(). Always switch back to default_content.
Do this now
Automate iframe page and multi-window link. Assert in correct context.
Dropdowns and alerts
Select class for dropdowns. Alert accept/dismiss. File upload send_keys to input[type=file].
Do this now
Cover dropdown, JavaScript alert, and file upload pages.