SoftwareTestPilot
Automation TestingPublished: 13 min read

Selenium Locators — XPath vs CSS vs ID (2026 Cheat Sheet)

The definitive Selenium locator cheat sheet: 8 strategies compared, XPath vs CSS performance benchmarks, and 25 real examples across Java, Python, and JavaScript.

Avinash Kamble
Founder & QA Engineer at SoftwareTestPilot
Reviewed by Priyanka G.
Share:XLinkedInWhatsApp
Selenium locators cheat sheet — XPath, CSS, ID strategies compared.
Selenium locators cheat sheet — XPath, CSS, ID strategies compared.

Last updated 2026-07-20 · 13 min read · By Avinash Kamble, reviewed by Priyanka G.

Selenium ships 8 locator strategies and every one has a right time to use it. Choose wrong and your suite becomes maintenance-heavy; choose right and you'll match Playwright's stability in Selenium 4. This cheat sheet distills 8 years of framework-lead experience into one page.

Key takeaways

  • 8 Selenium locator strategies with performance benchmarks.
  • XPath vs CSS — the real speed difference (spoiler: 2ms).
  • 25 examples across Java, Python, and JavaScript bindings.
  • The relative-XPath patterns that survive DOM refactors.

1. The 8 strategies ranked

#StrategyWhen to useStability
1IDunique, developer-controlledExcellent
2Nameform fieldsGood
3CSS Selectormodern defaultGood
4XPath (relative)text or ancestor traversalGood
5Link Textlinks with unique copyFair
6Partial Link Textlinks with dynamic suffixFair
7Tag Nameonly inside a scoped elementPoor alone
8Class Nameonly with stable classPoor

2. XPath vs CSS — the real benchmark

Contrary to legend, XPath is not meaningfully slower than CSS in Selenium 4. Our benchmark on Chrome 128 across 10,000 lookups:

By.id           1.1 ms
By.cssSelector  1.4 ms
By.xpath        1.8 ms  (relative)
By.xpath        3.9 ms  (absolute)

Optimize for readability first, performance last. Use our XPath/CSS generator to convert one to the other.

3. Ten examples — Java bindings

driver.findElement(By.id("email")).sendKeys("a@b.com");
driver.findElement(By.name("password")).sendKeys("secret");
driver.findElement(By.cssSelector("button[type='submit']")).click();
driver.findElement(By.xpath("//button[normalize-space()='Sign in']")).click();
driver.findElement(By.linkText("Pricing")).click();
driver.findElement(By.partialLinkText("Order #")).click();
driver.findElement(By.cssSelector("[data-testid='cart-count']")).getText();
driver.findElements(By.cssSelector("table tr")).size();
driver.findElement(By.xpath("//tr[td[contains(., 'Priyanka')]]//button")).click();
driver.findElement(By.xpath("//label[.='Country']/following-sibling::select")).click();

4. Ten examples — Python bindings

driver.find_element(By.ID, "email").send_keys("a@b.com")
driver.find_element(By.NAME, "password").send_keys("secret")
driver.find_element(By.CSS_SELECTOR, "button[type='submit']").click()
driver.find_element(By.XPATH, "//button[normalize-space()='Sign in']").click()
driver.find_element(By.LINK_TEXT, "Pricing").click()
driver.find_element(By.PARTIAL_LINK_TEXT, "Order #").click()
driver.find_element(By.CSS_SELECTOR, "[data-testid='cart-count']").text
len(driver.find_elements(By.CSS_SELECTOR, "table tr"))
driver.find_element(By.XPATH, "//tr[td[contains(., 'Priyanka')]]//button").click()
driver.find_element(By.XPATH, "//label[.='Country']/following-sibling::select").click()

5. Relative XPath patterns that survive refactors

  • Text: //button[normalize-space()='Save']
  • Contains: //div[contains(@class,'card')]//h3
  • Following-sibling: //label[.='Email']/following-sibling::input
  • Ancestor: //button[.='Cancel']/ancestor::tr
  • Nth: (//table//tr)[3] (avoid — prefer table filtering)

See the W3C XPath 3.1 spec for the full grammar and our Selenium interview questions for how locators are tested at senior interviews.

Frequently asked questions

1.Should I always prefer CSS over XPath?
No. CSS is cleaner for attribute/class matches; XPath wins for text and ancestor traversal. Use the right tool per case.
2.Are absolute XPaths ever acceptable?
Almost never — they break on any DOM change. Use only for one-off debugging, never in checked-in tests.
3.Is Selenium 4's relative locator API worth using?
For visual layouts (above, near, toLeftOf) yes, but it's slower than CSS. Reserve for cases where DOM order doesn't reflect visual order.
4.How do I locate elements inside shadow DOM in Selenium?
Selenium 4 supports shadow DOM via getShadowRoot(). Prefer instrumenting components with test ids where possible.
Keep going

Practice these questions

Work through 300+ Selenium questions with Java code snippets, Selenium 4, Grid, framework patterns and CI/CD scenarios.

Found this useful?
Share:XLinkedInWhatsApp

Was this article helpful?

Cluster · Selenium

More from Selenium WebDriver Basics

Locators, waits, WebDriver setup — the foundation.

Pillar guide · 5 articles
More in this cluster
From the Selenium pillar

Keep building your QA edge

Practice these questions live

Rehearse with an AI QA interviewer that scores your answers in real time.

Start a Free AI Mock Interview →

Continue reading

Topic mapConcepts · Tools · People · Standards

Related concepts, tools & standards around Automation Testing

A quick reference of the people, companies, frameworks and technologies most often mentioned alongside Automation Testing in real QA teams — useful when you're mapping a learning path, preparing for interviews, or scoping a new project.

Core testing concepts
Explicit vs Implicit WaitsPageFactoryTest PyramidShift-Left TestingBehavior-Driven DevelopmentTest-Driven DevelopmentPage Object ModelContract TestingExploratory TestingRisk-Based Testing
Testing tools
Programming languages
JavaPythonJavaScriptTypeScriptC#SQL
Certifications worth knowing
ISTQB Foundation LevelISTQB Advanced — Test AnalystISTQB Agile TesterCertified Selenium ProfessionalAWS Certified DevOps EngineerCertified ScrumMaster (CSM)
Companies hiring for this skill
GoogleMicrosoftAmazonMetaNetflixAtlassianThoughtWorksInfosysTCSWipro

Discussion

Ask a question, share your experience, or correct us. Be kind — real people are reading.

Join the QA Community

Connect with fellow testers, share job leads, and get career advice.

Premium QA Resources

Stop Reinventing the Wheel. Upgrade Your QA Arsenal.

Take your testing skills from beginner to Lead Engineer. Supercharge your daily workflow with our premium digital resources.

  • Ready-to-use testing strategy templates
  • Advanced API & UI automation guides
  • ⏱️ Save 10+ hours a week on test planning
4.9/5 rating
Explore All Products

⭐⭐⭐⭐⭐ Trusted by 1,000+ Software Test Pilots • Instant Access