SE
XPath

Selenium XPath Cheat Sheet

ABSOLUTE · RELATIVE · ATTRIBUTES · FUNCTIONS · AXES · CSS SELECTOR · TIPS & TRICKS · INTERVIEW READY

🎓 Next Gen QA IT Coaching Classes
📞 Mr. Khan Sir  |  8700350994
Selenium & XPath Playwright & API Testing Online & Offline B.Tech / BCA / MCA CBSE / ICSE / Polytechnic
XPath Basics · Absolute vs Relative · Syntax · How to Use in Selenium
What is XPath?
Definition
XPath (XML Path Language) is a syntax to navigate through elements and attributes in an HTML/XML document to locate web elements in Selenium.
Why XPath?
When elements don't have a unique ID, name or class — XPath can locate ANY element using its position, text, attributes or relationships.
XPath in Selenium
Used inside By.xpath("...") to find elements. Works with findElement() and findElements().
XPath Syntax Structure
// XPath Syntax Axis::NodeName[@Attribute='Value'] // Examples // 1. Tag + Attribute //input[@id='username'] // 2. Tag + Text //button[text()='Login'] // 3. Any tag with attribute //*[@placeholder='Enter email']
Absolute vs Relative XPath
Absolute XPathRelative XPath
Starts with/html/body/...//tagname
Starting pointRoot of documentAnywhere in DOM
Fragile?YES — breaks easilyNO — robust
Recommended?❌ Never use✅ Always use
SpeedSlowFast
Examples
// ❌ Absolute — NEVER USE (brittle!) /html/body/div[1]/form/div/input[2] // ✅ Relative — ALWAYS USE //input[@id='username'] //button[@type='submit'] //div[@class='login-form']//input
How to Use in Selenium
// Single element WebElement el = driver.findElement( By.xpath("//input[@id='username']")); // Multiple elements List<WebElement> els = driver.findElements( By.xpath("//ul[@class='menu']/li"));
XPath by Attributes
All attribute-based XPath patterns
// By id //input[@id='username'] // By name //input[@name='email'] // By class //button[@class='btn-primary'] // By type //input[@type='submit'] // By placeholder //input[@placeholder='Enter phone'] // By href //a[@href='https://example.com'] // By value //input[@value='Submit'] // By disabled attribute //input[@disabled] // By data-* attribute //div[@data-id='123'] //button[@data-testid='login-btn'] // Any tag with attribute //*[@id='submit'] //*[@class='active']
XPath by Text
Locating elements using visible text
// Exact text match //button[text()='Login'] //a[text()='Click Here'] //h1[text()='Welcome'] // Using normalize-space (handles spaces) //button[normalize-space()='Log In'] // Text with contains() //button[contains(text(),'Log')] //a[contains(text(),'Click')] //*[contains(text(),'Submit')] // starts-with text //p[starts-with(text(),'Welcome')] // Case-sensitive — exact case needed! // 'login' ≠ 'Login' ≠ 'LOGIN' // Partial text in any tag //*[contains(text(),'error')] // Label text //label[text()='User Name']
XPath Functions — contains() · starts-with() · text() · normalize-space() · position() · last() · count()
contains() Function
Most important XPath function — partial match
// Syntax: contains(@attr, 'value') // Syntax: contains(text(), 'value') // Attribute contains value //input[contains(@id,'user')] //div[contains(@class,'active')] //a[contains(@href,'login')] //input[contains(@placeholder,'email')] // Text contains value //button[contains(text(),'Login')] //span[contains(text(),'Error')] // Multiple classes (very common!) //div[contains(@class,'btn') and contains(@class,'primary')] // Real world example // Find: <input id="user_name_field"> //input[contains(@id,'user')]
starts-with() Function
// Syntax: starts-with(@attr, 'value') // ID starts with //input[starts-with(@id,'user')] //div[starts-with(@class,'btn')] // href starts with //a[starts-with(@href,'https')] // Text starts with //p[starts-with(text(),'Welcome')] //h2[starts-with(text(),'Error')] // Dynamic IDs — very useful! // Find: <td id="row_1_col_3"> //td[starts-with(@id,'row_')]
AND / OR Conditions
// AND — both conditions must be true //input[@type='text' and @name='q'] //button[@type='submit' and contains(@class,'primary')] //*[@id='x' and contains(text(),'OK')] // OR — either condition can be true //input[@id='email' or @id='phone'] //button[text()='OK' or text()='Confirm'] // NOT — negate a condition //input[not(@disabled)] //div[not(contains(@class,'hidden'))] // Combined AND + OR //input[(@type='text' or @type='email') and @required]
position() and last() Functions
// By position — index starts at 1! // Get 2nd row in table //table/tbody/tr[2] // Shorthand for position() //ul/li[position()=1] ← first item //ul/li[position()=2] ← second item // last() — get last element //ul/li[last()] //tr[last()]/td[1] // last()-1 = second to last //ul/li[last()-1] // count() — count child elements //ul[count(li)=5] ← ul with 5 li items // Multiple elements with index // 3rd input on page (//input[@type='text'])[3] (//button)[1] ← first button (//a)[last()] ← last anchor tag
normalize-space() & string-length()
// normalize-space — trims whitespace // Handles: " Login " = "Login" //button[normalize-space()='Login'] //td[normalize-space()='John Doe'] // normalize-space with text() //*[normalize-space(text())='Submit'] // string-length — check text length //input[string-length(@value)>0] //p[string-length(text())>10] // translate() — case-insensitive match //button[translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') ='login'] // substring() — part of string //*[substring(@id,1,4)='user'] // Gets first 4 chars of @id
XPath with Multiple Attributes
// Combine class + type + name //input[@type='text' and @class='form-control'] // Attribute + text combo //a[@class='nav-link' and text()='Home'] // Data attributes //button[@data-testid='submit'] //div[@data-role='dialog'] // Aria attributes (accessibility) //button[@aria-label='Close'] //div[@role='alert'] //input[@aria-required='true']
XPath for Dynamic Elements
// Dynamic ID patterns // e.g. id="user_1234_field" //input[contains(@id,'user') and contains(@id,'field')] // Auto-generated classes // e.g. class="btn btn-primary btn-lg" //button[contains(@class,'btn-primary')] // Timestamp-based IDs // e.g. id="modal_1709123456" //div[starts-with(@id,'modal_')] // React/Angular generated IDs //*[contains(@id,'react-select')] //*[contains(@class,'ng-')] // Using visible text (most stable) //button[contains(text(),'Submit')] //td[contains(text(),'John')]
XPath Operators
OperatorMeaningExample
=Equal to@id='name'
!=Not equal@type!='hidden'
<Less than@count<5
>Greater than@size>10
andBoth true@a='x' and @b='y'
orEither true@a='x' or @a='y'
not()Negatenot(@disabled)
|Union (both)//a | //button
XPath Axes — parent · child · following-sibling · preceding-sibling · ancestor · descendant · following · preceding
What are XPath Axes?
Definition
XPath Axes define the RELATIONSHIP between current node and target node. Used to navigate the DOM tree in any direction.
Syntax
//currentNode/axis::targetNode[@attribute]
All XPath Axes — Quick Reference
AxisWhat it selects
parentDirect parent node
childDirect children only
following-siblingSiblings AFTER current node
preceding-siblingSiblings BEFORE current node
ancestorAll ancestors up to root
descendantAll children, grandchildren
followingAll nodes after in document
precedingAll nodes before in document
selfCurrent node itself
ancestor-or-selfSelf + all ancestors
descendant-or-selfSelf + all descendants
parent:: and child:: Axes
// parent:: — go UP to parent // Find parent div of an input //input[@id='email']/parent::div // Find label's parent form //label[text()='Email']/parent::form // Any parent tag //input[@id='un']/parent::* // child:: — go DOWN to children // Find direct li children //ul[@class='menu']/child::li // Same as / shorthand //ul[@class='menu']/li ← same thing // Find all child inputs in form //form[@id='login']/child::input
ancestor:: Axis
// ancestor:: — any ancestor going UP // Find table ancestor of a cell //td[text()='John']/ancestor::table // Find form ancestor of button //button[@type='submit']/ancestor::form // ancestor-or-self //input/ancestor-or-self::div // Self axis //input[@id='x']/self::input
following-sibling:: Axis
Most used axis — find next sibling elements
// following-sibling — after current node // MOST COMMON USE CASE: // Find input next to a label // HTML: <label>Email</label><input...> //label[text()='Email']/ following-sibling::input // Find button next to error span //span[text()='Error']/ following-sibling::button // Find td next to "Name" td //td[text()='Name']/ following-sibling::td // First following sibling //label[text()='Phone']/ following-sibling::input[1] // Any following sibling //li[1]/following-sibling::li
preceding-sibling:: Axis
// preceding-sibling — before current node // Find label before input //input[@id='email']/ preceding-sibling::label // Find td before a specific cell //td[text()='100']/ preceding-sibling::td[1] // Gets the td immediately before // Find heading before a list //ul[@class='items']/ preceding-sibling::h2
descendant:: & following:: Axes
// descendant:: — any level below // All inputs inside a div //div[@id='form']/ descendant::input // Same as // shorthand //div[@id='form']//input ← same! // All buttons anywhere in section //section[@class='main']/ descendant::button // following:: — all nodes after // (different from following-sibling) // Includes nested children too //h1[text()='Login']/ following::input // Gets ALL inputs anywhere after h1 // preceding:: — all nodes before //button[@id='submit']/ preceding::input
Real World Axes Examples
// SCENARIO 1: // Click Edit for row with "John" // HTML: <td>John</td><td><button>Edit</button></td> //td[text()='John']/ following-sibling::td/ button[text()='Edit'] // SCENARIO 2: // Find input by label name // HTML: <label>Mobile</label><input> //label[contains(text(),'Mobile')]/ following-sibling::input // SCENARIO 3: // Delete button in specific table row //tr[td[text()='Alice']]/ descendant::button[text()='Delete']
CSS Selectors — All Patterns · Attribute · Pseudo-classes · XPath vs CSS Comparison
CSS Selector Basics
// By ID — prefix: # By.cssSelector("#username") // Finds: <input id="username"> // By Class — prefix: . By.cssSelector(".btn-submit") // Finds: <button class="btn-submit"> // By Tag name By.cssSelector("input") // By Tag + ID By.cssSelector("input#email") // By Tag + Class By.cssSelector("button.btn-primary") // Multiple classes By.cssSelector(".btn.btn-lg.active") // Tag + ID + Class By.cssSelector("input#email.form-ctrl")
CSS Attribute Selectors
// Exact attribute value By.cssSelector("input[type='email']") By.cssSelector("a[target='_blank']") // Attribute exists (any value) By.cssSelector("input[required]") By.cssSelector("input[disabled]") // Contains: *= By.cssSelector("input[id*='user']") By.cssSelector("a[href*='login']") // Starts with: ^= By.cssSelector("input[id^='user']") By.cssSelector("a[href^='https']") // Ends with: $= By.cssSelector("input[id$='field']") By.cssSelector("img[src$='.png']") // Word match: ~= By.cssSelector("div[class~='active']")
CSS Child & Descendant
// Direct child: > By.cssSelector("form > input") // Only direct input children of form // Any descendant: space By.cssSelector("form input") // All inputs anywhere inside form // Adjacent sibling: + By.cssSelector("label + input") // Input immediately after a label // General sibling: ~ By.cssSelector("label ~ input") // All inputs that are siblings of label // Deep nested By.cssSelector("div.form > div > input") By.cssSelector("table tbody tr td a")
CSS Pseudo-classes
// :nth-child — 1-based index By.cssSelector("ul li:nth-child(1)") By.cssSelector("tr:nth-child(3) td") // :first-child / :last-child By.cssSelector("li:first-child") By.cssSelector("tr:last-child") // :nth-of-type By.cssSelector("p:nth-of-type(2)") // :not() — exclude elements By.cssSelector("input:not([disabled])") By.cssSelector("li:not(.active)") // :checked (checkbox/radio) By.cssSelector("input:checked") // :enabled / :disabled By.cssSelector("input:enabled") By.cssSelector("button:disabled")
XPath vs CSS Selector
FeatureXPathCSS Selector
DirectionBoth ways (up & down)Down only
Text search✅ text()❌ Not supported
Axes✅ parent, siblingLimited
SpeedSlowerFaster
SyntaxComplexSimpler
Browser supportAllAll
Containscontains()*=
Starts-withstarts-with()^=
Ends-withNo (use substring)$=
nth element[position()=n]:nth-child(n)
Use CSS when
Locating by ID, class, attribute, or tag. Faster and simpler for most cases.
Use XPath when
Need to search by text, navigate parent/sibling, or handle complex dynamic elements.
How to Find & Test XPath in Browser
Step 1 — Open DevTools
Press F12 or Right-click → Inspect Element
Step 2 — Open Console Tab
Click the Console tab in DevTools
Step 3 — Test XPath
Type: $x("//input[@id='email']") and press Enter. Shows matching elements.
Step 4 — Test CSS
Type: $$("input#email") and press Enter. Shows matching elements.
Step 5 — Highlight on Page
Hover over result in console — element highlights on the page!
Browser Console Commands
// Test XPath in browser console $x("//input[@id='username']") $x("//button[text()='Login']") $x("//div[contains(@class,'active')]") // Test CSS in browser console $$("input#email") $$("button.btn-primary") $$("input[type='text']") // Check count of elements $x("//li").length $$("li").length
XPath Interview Questions · Pro Tips · Common Mistakes · Best Practices
XPath Interview Q&A — Part 1
Q: What is XPath?
XPath is XML Path Language used to navigate and locate elements in HTML/XML documents. Used in Selenium via By.xpath().
Q: Absolute vs Relative XPath?
Absolute starts from root /html/body... (brittle). Relative starts from anywhere //tagname (recommended, robust).
Q: What is contains() in XPath?
Function to match partial attribute or text value. e.g. //input[contains(@id,'user')] — finds elements where id contains 'user'.
Q: What are XPath Axes?
Axes define relationships between nodes: parent, child, following-sibling, preceding-sibling, ancestor, descendant.
Q: How to find dynamic elements?
Use contains() for partial ID match, starts-with() for prefix match, or locate by stable attributes like text content.
Q: // vs / in XPath?
/ = direct child only. // = anywhere in document (any descendant). //div means find div anywhere in HTML.
Q: What is * in XPath?
Wildcard — matches any tag. //*[@id='x'] finds any element with id='x' regardless of tag name.
XPath Interview Q&A — Part 2
Q: XPath vs CSS Selector?
XPath can navigate UP (parent/sibling) and search by text. CSS is faster and simpler but can only go down the DOM. Use CSS for simple cases, XPath for complex ones.
Q: How to find sibling elements?
Use following-sibling:: (after) or preceding-sibling:: (before). e.g. //label[text()='Email']/following-sibling::input
Q: How to locate nth element?
Use index in brackets: (//button)[2] for 2nd button, or //tr[position()=3] for 3rd row, or //tr[last()] for last row.
Q: How to handle multiple classes?
Use contains() for each class: //div[contains(@class,'btn') and contains(@class,'active')]. Never use = for multiple classes.
Q: What is normalize-space()?
Trims leading/trailing whitespace from text. Useful when button text has spaces. //button[normalize-space()='Login']
Q: How to test XPath without running Selenium?
In browser DevTools Console: $x("your-xpath") to test XPath. $$("your-css") to test CSS selectors instantly.
Pro Tips & Best Practices
✅ Prefer ID or Name first
Always check if element has unique id or name. By.id() and By.name() are fastest and most reliable.
✅ Use Relative XPath always
Never use Absolute XPath. One small page change breaks it. Always use // to start.
✅ Prefer CSS over XPath
When text search not needed — CSS selector is faster and simpler than XPath.
✅ Use data-testid attributes
Ask developers to add data-testid="login-btn" attributes. Most stable for automation.
✅ Test in browser first
Always validate XPath in browser console using $x() before writing Selenium code.
✅ Avoid index-based XPath
XPath like //div[3]/input[2] breaks when page structure changes. Use attribute-based instead.
✅ Use normalize-space()
When button text might have extra spaces — always use normalize-space() to avoid failures.
Common XPath Mistakes
❌ Using Absolute XPath
/html/body/div[1]/form/input — Breaks immediately when page changes. Never use this!
❌ = for multiple classes
//div[@class='btn primary active'] — FAILS if class order changes. Use contains() for each class instead.
❌ Wrong case in text()
XPath is case-sensitive. //button[text()='login'] won't find 'Login'. Match exact case always.
❌ Missing parentheses for index
//button[2] ≠ (//button)[2]. First finds 2nd button child. Second finds 2nd button globally. Use (//tag)[n] for global nth.
❌ Index starts at 0
XPath index starts at 1, NOT 0! //tr[1] is first row. //tr[0] returns nothing!
❌ Forgetting // before axis
Wrong: /label/following-sibling::input. Correct: //label/following-sibling::input. Always use // to start.
Locator Priority Guide
PriorityLocatorUse When
1stBy.id()Element has unique ID
2ndBy.name()Element has name attr
3rdBy.cssSelector()No text search needed
4thBy.xpath()Need text / axes
5thBy.className()Unique single class
LastBy.tagName()Only one of that tag