Every time you need to find an element, follow this checklist from top to bottom. Stop at the first one that works.
Modern apps add data-testid attributes specifically for automation. They're the gold standard because: (1) they exist only for testing — devs don't touch them during UI changes, (2) they're never auto-generated or dynamic, (3) they survive CSS refactors. Both the Banking and Shopping portals use data-testid extensively.
// data-testid — access via CSS selector
WebElement loginBtn = driver.findElement(
By.cssSelector("[data-testid='loginBtn']"));
WebElement searchBox = driver.findElement(
By.cssSelector("[data-testid='search-box']"));
WebElement productName = driver.findElement(
By.cssSelector("[data-testid='product-name-1']"));
// Same thing with XPath (slightly slower)
WebElement loginBtnXPath = driver.findElement(
By.xpath("//*[@data-testid='loginBtn']"));If you have any influence on the app, ask developers to add data-testid to key elements. Most frontend devs understand this — React, Angular, and Vue communities all recommend it. It's not extra work for them, and it saves you hours.
Key Point: Priority: id → data-testid → name → CSS selector → XPath. Always start from the top.