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

Selenium Locators Cheat Sheet: Strategies, Examples, and Selection Tips

A practical Selenium locator reference with all eight traditional strategies, selection advice, Python examples, relative locators, shadow-root searches, and common fixes.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a unique, predictable id when the page provides one. Otherwise, Selenium recommends a well-written CSS selector; use XPath when its flexibility is needed, and verify that your locator does not match unintended elements. This cheat sheet covers Selenium’s eight traditional locator strategies, Selenium 4 relative locators, lookup behavior, and practical examples.

Selenium locator strategies at a glance

Selenium WebDriver has eight traditional locator strategies. The examples below use Python’s Selenium API, with the same strategy names applying across WebDriver language bindings.

Strategy What it matches Example Watch for
id An element whose id attribute matches the supplied value. By.ID, "email" Prefer an ID that is unique and consistently predictable.
name An element whose name attribute matches the supplied value. By.NAME, "username" Use it when the page provides an appropriate name.
class name An element with the specified class. By.CLASS_NAME, "submit-button" Supply one class name; a compound class string is not permitted.
css selector Elements matching a CSS selector. By.CSS_SELECTOR, "form#login input[name='email']" Prefer a compact, readable selector. Selenium recommends CSS when a suitable unique ID is unavailable.
xpath Elements matching an XPath expression. By.XPATH, "//input[@name='email']" Flexible, but Selenium notes that XPath syntax can be more complicated and harder to debug.
link text An anchor whose visible text exactly matches. By.LINK_TEXT, "Privacy policy" Works only on links; exact copy must remain stable.
partial link text An anchor whose visible text contains the supplied text. By.PARTIAL_LINK_TEXT, "Privacy" Works only on links and may match more than one link.
tag name Elements with the requested tag. By.TAG_NAME, "button" Often matches many elements, so it is mainly useful for collection lookups.

These strategies and their scope are documented in Selenium’s locator strategies reference.

How to choose a locator

  1. Check for a stable, unique ID. Selenium says: “In general, if HTML IDs are available, unique, and consistently predictable, they are the preferred method for locating an element on a page.” See Selenium’s locator guidance.
  2. Use a readable CSS selector if there is no suitable ID. Keep it focused on meaningful attributes and relationships rather than relying on a long chain of incidental containers.
  3. Choose XPath when its flexibility solves a real need. It can express relationships and conditions that are useful for a particular page, but its added flexibility may make selectors harder to read and debug.
  4. For links, decide whether exact or partial text is safer. Exact text is more specific but depends on the whole visible label; partial text can survive some copy changes but risks matching another link.
  5. Be cautious with broad classes and tag names. If the locator can match several elements, narrow it or retrieve a collection and inspect the results.

CSS selector or XPath?

Both can locate elements by attributes and relationships. Selenium’s guidance favors a well-written CSS selector when a suitable unique ID is unavailable, while noting XPath’s greater flexibility and debugging complexity. The cited documentation does not establish that one is universally faster, so choose based on clarity and the match you need rather than assuming a speed advantage.

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

Python examples: find one element or a collection

Install the Selenium Python package and have a compatible browser and driver setup before running this example. It opens a page, finds an element by ID, and collects matching buttons:

from selenium import webdriver
from selenium.webdriver.common.by import By

with webdriver.Chrome() as driver:
    driver.get("https://example.com")

    heading = driver.find_element(By.ID, "main-heading")
    print(heading.text)

    buttons = driver.find_elements(By.TAG_NAME, "button")
    print(f"Found {len(buttons)} buttons")

Replace the example URL and locator values with elements that exist on your target page. The singular find_element call returns the first match in the current search context; it does not prove the match is unique. Use find_elements when you expect or need to inspect multiple matches. Selenium documents this behavior in Finding web elements.

Common Python locator forms

By.ID, "email"
By.NAME, "username"
By.CLASS_NAME, "submit-button"        # one class name only
By.CSS_SELECTOR, "input[name='email']"
By.XPATH, "//input[@name='email']"
By.LINK_TEXT, "Privacy policy"         # exact link text
By.PARTIAL_LINK_TEXT, "Privacy"        # partial link text
By.TAG_NAME, "button"

Relative locators in Selenium 4

Selenium 4 also provides relative locators: above, below, to_left_of, to_right_of, and near. They locate a target by its position relative to an element you can identify more easily. Selenium uses getBoundingClientRect() to determine element size and position for this feature; see the official locator reference.

Use relative location when visual placement is genuinely the relationship your test needs. It is not a substitute for a stable semantic locator when one is available: layout changes can alter which element is above, below, or near another.

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

Nested elements and shadow roots

Scope a lookup to a parent

You can locate a parent element first, then search within it. This makes the intended scope explicit, but may require two browser commands. Selenium notes that a CSS or XPath selector can sometimes describe the same search in one command and improve performance slightly. Keep the one-command selector readable rather than turning it into an unnecessarily long DOM traversal.

Search inside a shadow root

For a shadow-DOM element, first locate its host, obtain the host’s shadow root, and search within that root. Selenium’s shadow-root finder methods require Selenium 4 or later.

host = driver.find_element(By.CSS_SELECTOR, "my-widget")
shadow_root = host.shadow_root
button = shadow_root.find_element(By.CSS_SELECTOR, "button")

The host selector and inner selector must match the actual page. See Selenium’s finder reference for search contexts and shadow-root methods.

Common locator problems and fixes

  • The wrong element is selected: a singular lookup returns the first match. Make the selector more specific, or use a collection lookup and check its members.
  • A class-name lookup rejects the value: class-name strategy takes one class, not a space-separated compound string. Use a CSS selector such as .primary.submit when matching multiple classes is needed.
  • Link text finds nothing: link-text strategies only apply to anchors. Confirm the visible text and whether exact or partial matching is appropriate; for non-links, use another strategy.
  • A tag-name lookup returns too many results: tags such as button are commonly repeated. Scope the search or use a more specific attribute selector.
  • An XPath is difficult to maintain: simplify it or use a readable CSS selector if it expresses the same target. Avoid deep paths tied to incidental page structure.
  • A nested search is slower than expected: a parent lookup followed by a child lookup can require two commands. Where clarity allows, express the relationship in one CSS or XPath locator.
  • A relative locator becomes unreliable after layout changes: it depends on spatial relationships. Prefer a stable ID or semantic selector if the target has one.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is to capture a page rather than automate interaction with its elements, ScreenshotNeo provides a website screenshot API and MCP server. A single GET request can return a PNG, JPEG, WebP, or PDF. For example, this cURL request saves a WebP screenshot; see the ScreenshotNeo documentation for parameters.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
  • Cookie/consent banners are accepted and removed, along with supported newsletter popups and chat widgets, before capture; each step can be turned off.
  • Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed. Responses include X-Page-Verdict and X-Billed headers.
  • An MCP server exposes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.
  • The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots.

Sign up for ScreenshotNeo’s free plan.

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 *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

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

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. 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…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

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.