October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk6 min

XPath Locators Cheat Sheet: Syntax and Examples for Selenium

Learn XPath paths, predicates, functions, axes, and Selenium locator patterns, plus how to choose and troubleshoot readable, stable expressions.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

XPath locators identify elements by their place in a document tree, attributes, text, or relationships to other elements. For Selenium, use a unique, predictable ID when one is available; choose a clear CSS selector next when it is not. Reach for XPath when its ability to match text or navigate between related elements makes the locator simpler and more reliable.

XPath locator syntax at a glance

An XPath location step consists of an axis, a node test, and optional predicates. The axis says which direction to search, the node test says what kind of node to match, and predicates filter the results. XPath supports paths through XML-like documents, including HTML and SVG DOMs; Selenium exposes XPath as one of its WebDriver locator strategies. See MDN’s XPath overview and Selenium’s locator strategies.

Syntax Meaning Example
/ Separates path steps; a leading slash starts at the document root. /html/body
// Abbreviates a search through descendants. //button
child:: Selects child nodes; the child axis is assumed if no axis is written. child::button
@ Abbreviates the attribute axis. @name
[...] Filters matches with a predicate. input[@name='email']

For example, //input[@name='email'] means: search descendants for input elements whose name attribute equals email. These expressions are syntax examples, not tested against a live page; what matches depends on the target DOM and XPath implementation.

Common XPath patterns

Need XPath How it reads
Find elements by tag //button Find button elements among the document’s descendants.
Match an exact attribute value //input[@name='email'] Find inputs with the specified name.
Match an attribute substring //button[contains(@class, 'primary')] Match buttons whose class attribute contains that text. This may also match unintended values such as not-primary; for a class token, use a whitespace-aware expression or another locator strategy.
Match normalized text //button[normalize-space()='Save'] Match buttons whose normalized string value is Save.
Match a text fragment //a[contains(., 'Documentation')] Find links whose string value contains the fragment.
Require both conditions //input[@type='text' and @name='email'] Match inputs satisfying both predicates.
Require either condition //button[@type='submit' or @aria-label='Save'] Match buttons satisfying at least one predicate.
Select the first result in a group (//button[@type='submit'])[1] Parentheses group the results before selecting position one.

Predicates, positions, and context

A predicate in square brackets filters the nodes selected by a step. Numeric positions are one-based: [1] is the first match, not the zeroth. Position can depend on the axis context and grouping, so parentheses matter.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
  • //button[1] selects button elements that are first among the relevant button nodes for each parent context.
  • (//button)[1] selects the first button in the grouped result across the document.
  • position() returns a node’s position in the current context; last() returns the context’s final position.

For a reverse axis, preceding::foo[1] and (preceding::foo)[1] can select different nodes because the predicate is evaluated in a different context after grouping. The W3C’s XPath 1.0 working draft describes location steps and predicate semantics; use it for the XPath 1.0 constructs shown here, not as a reference to later XPath versions.

XPath functions worth knowing

Function or test Example Use
contains() //a[contains(., 'Docs')] Match when a string contains a fragment.
starts-with() //input[starts-with(@name, 'account-')] Match an attribute or string beginning with a prefix.
normalize-space() //button[normalize-space()='Save'] Trim leading and trailing whitespace and collapse runs of whitespace before comparing.
text() //button[text()='Save'] Test direct text-node children; it may not match when text is nested inside child elements.
position() and last() //li[position()=last()] Test a node’s position within the current context.

Text matching depends on the document tree and XPath implementation. For a practical reference to XPath functions and axes, see MDN’s XPath reference.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Use axes to locate related elements

Axes let XPath move from one node to another through the document tree. The thirteen XPath axes include the following commonly useful ones.

Axis Direction or scope Example
child:: Direct children; the default axis. child::input
parent:: The parent node. parent::div
self:: The context node itself. self::button
descendant:: Nodes below the context node. descendant::input
ancestor:: Nodes above the context node. ancestor::tr
following-sibling:: Later siblings of the context node. following-sibling::input
preceding-sibling:: Earlier siblings of the context node. preceding-sibling::label
following:: Later nodes in document order, subject to axis semantics. following::button
preceding:: Earlier nodes in document order, subject to axis semantics. preceding::h2
attribute:: Attributes; commonly abbreviated with @. attribute::name or @name

Connect an input to a label

//label[normalize-space()='Email']/following-sibling::input finds an input that follows a matching label as a sibling. It only works if the page actually structures the label and input that way; a wrapping label or a separate container needs a different path.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Find a containing row

//span[normalize-space()='Total']/ancestor::tr[1] starts from a span with the text “Total” and selects a nearby matching ancestor row. The exact result depends on the axis and DOM structure.

Prefer a short relationship from a stable, distinctive element over a long path tied to many layout details. A locator based on a label, row, or container can be useful when the target itself has no stable identifier.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Choose XPath or another Selenium locator

XPath is useful when the target is best identified by text or by a relationship such as ancestor and sibling navigation. It is not automatically the best choice for every element. Selenium’s official guidance says predictable, unique IDs are preferred when available, followed by a good CSS selector if IDs are absent. Selenium also notes that XPath can be harder to debug and that performance may be slow, particularly for complicated DOM traversals; that is practical guidance, not a universal speed ranking. See Selenium’s tips on working with locators (last modified February 10, 2022).

  • Stability: Prefer a stable ID, test attribute, or accessible name over a selector that depends on changing layout positions.
  • Readability: Keep expressions compact enough that a teammate can understand their target and conditions.
  • Navigation: Use XPath when moving to an ancestor or sibling makes the relationship clearer than a CSS selector.
  • Text matching: XPath predicates and functions can identify content when attribute-based alternatives are not suitable.
  • Scope: Narrow searches to a stable parent container where possible, then locate the child within that scope.
  • Debuggability: If a DOM change makes the expression difficult to repair, simplify it or choose a more stable locator.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use XPath in Selenium

In Selenium, pass the XPath expression to the WebDriver XPath locator strategy. This short Python example shows the form; the selector assumes the page has a matching email input.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
try:
    driver.get("https://example.com")
    email = driver.find_element(By.XPATH, "//input[@name='email']")
    email.send_keys("[email protected]")
finally:
    driver.quit()

Replace the example address with the page under test and use an expression that matches its actual DOM. Selenium’s locator documentation covers the WebDriver-specific usage.

Troubleshoot XPath that finds nothing or the wrong element

  • No match: Inspect the live DOM and confirm the element exists in the document Selenium is querying. Check tag and attribute spelling, exact text, and whether the label/input or ancestor/sibling relationship in the expression matches the actual tree.
  • Wrong match: Add a distinctive predicate or scope the search beneath a stable container. Avoid broad substring checks when they can match unintended attribute values.
  • Text mismatch: Check for nested elements or whitespace. text() tests direct text-node children; normalize-space() can help with whitespace, while . tests the element’s string value.
  • Unexpected first result: Check whether the position predicate applies per context or to a parenthesized result set. XPath positions start at one.
  • Fragile expression: Replace deep positional paths with a stable ID, suitable CSS selector, or a short relationship to a distinctive label or container.

XPath expressions are evaluated against a particular document tree, so a correct expression for one page structure may not match another. The examples above are reference patterns, not claims of live-page testing.

Or skip the browser setup

If your goal is to capture a page rather than write a Selenium locator, ScreenshotNeo returns a screenshot or PDF from one GET request. Cookie and consent banners, newsletter popups, and chat widgets are removed before capture; each step can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers indicate the page verdict and billing status. Its MCP server gives AI agents tools to take screenshots, get page information, and capture PDFs.

cURL example:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp

See the ScreenshotNeo API documentation for setup and options. Plans include 1,000 screenshots per month free with no card; paid plans start at $5 for 3,000. Learn about ScreenshotNeo or sign up for the free plan.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Does XPath use zero-based or one-based indexes?

XPath positions are one-based: the first position is 1.

Does Selenium require XPath for text-based locators?

No. XPath supports text predicates, but choose a locator strategy that is stable and readable for the page and test.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.