October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

Selenium 4 Relative Locators: How to Find Web Elements

Selenium 4 relative locators use rendered position to find an element above, below, left, right, or near a known reference. See Python examples and practical limits.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Selenium 4 relative locators find a candidate element by its position in relation to another element you can already locate—for example, a button below an email field. Use them when a spatial relationship is easier to express than a direct locator, and remember that the relationship depends on the elements’ rendered positions.

What Selenium 4 relative locators do

Relative locators combine two things: a locator for the elements you want to consider and a spatial relationship to a known reference element. Selenium calls these Relative Locators; they were previously called “Friendly Locators.” The Selenium locator guide explains that Selenium uses JavaScript getBoundingClientRect() to determine element size and position, then uses that geometry to find neighboring elements.

This makes a relative locator useful when the target is hard to identify directly but its position beside a known element is clear. It does not make a target intrinsically unique: if several elements satisfy the relationship, you may need to narrow the candidate locator or add another spatial filter.

Which spatial relationships are available?

Relationship Meaning
above Find a candidate above the reference element.
below Find a candidate below the reference element.
toLeftOf Find a candidate to the left of the reference element.
toRightOf Find a candidate to the right of the reference element.
near Find a candidate close to the reference element.

The reference point can be an ordinary locator or an element you have already found. The exact method spelling and syntax differ across Selenium bindings; the example below uses Python.

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

Find an element with a relative locator in Python

In the example, the email field is located by its ID, and the target button is identified as a button below it. The code assumes you have already created a Selenium WebDriver instance named driver and opened the page under test.

from selenium.webdriver.common.by import By
from selenium.webdriver.support.relative_locator import locate_with

email_field = driver.find_element(By.ID, "email")
submit_button = driver.find_element(
    locate_with(By.TAG_NAME, "button").below(email_field)
)
submit_button.click()

The candidate locator here is By.TAG_NAME, "button"; the reference element is email_field; and below(email_field) supplies the spatial condition. Selenium’s Python API reference for version 4.50.0 documents the same general form, including locate_with(By.CSS_SELECTOR, "p").above(element).

Use a locator as the reference

You can also pass a locator as the reference instead of finding the reference element first. For example, the Python pattern is locate_with(By.TAG_NAME, "button").below({By.ID: "email"}). Passing a previously found element is useful when you already need that element for another part of the test; passing a locator can keep a short lookup in one expression.

Chain relationships to narrow the result

When one relationship matches too many candidates, chain another filter. Selenium documents combining relationships—for example, constraining a button to be below an email field and to the right of a cancel button. This expresses both conditions instead of relying on whichever matching button happens to be returned.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
email_field = driver.find_element(By.ID, "email")
cancel_button = driver.find_element(By.ID, "cancel")

submit_button = driver.find_element(
    locate_with(By.TAG_NAME, "button")
    .below(email_field)
    .to_right_of(cancel_button)
)

Set the distance for near

In Selenium’s Python binding, near defaults to 50 pixels. You can supply a distance in pixels when the default is not appropriate; the Python API reference says the distance must be positive, so zero or a negative value is invalid.

help_icon = driver.find_element(
    locate_with(By.CSS_SELECTOR, "button").near(email_field, 80)
)

Use a distance that matches the layout you intend to test. A larger radius can include more nearby candidates, so combine near with a more specific candidate locator or another relationship if needed.

When relative locators are a good fit

  • Use one when: a stable reference element is easy to locate, while the target is naturally described as above, below, left, right, or nearby.
  • Prefer a direct CSS or XPath locator when: the target has a clear, stable attribute or structural path. A direct locator states what the element is; a relative locator states where it appears in the rendered layout.
  • Be cautious when: responsive layouts, viewport changes, or page content changes can move elements. Relative locators reason from rendered geometry, so check that the relationship remains meaningful at the viewport used by the test.

These are practical trade-offs, not a claim that relative locators are faster or more reliable. Selenium’s documentation describes their purpose and geometry, but does not establish comparative performance or reliability measurements.

Troubleshoot relative-locator failures

No element matches

  • Confirm that the reference element is present and that your ordinary locator finds it.
  • Check the page at the test’s current viewport: the target may not actually be on the expected side after responsive reflow.
  • Check that the candidate locator describes the target’s element type or attributes, and that the intended spatial relationship is accurate.

The wrong candidate is found

  • Narrow the candidate locator instead of searching every element of a broad type such as button.
  • Chain another relationship when multiple candidates satisfy the first one.
  • Reconsider whether layout position uniquely identifies the target. If it does not, use a direct locator based on a stable attribute or structure.

near raises an error or matches too broadly

  • For Python, provide a positive distance; zero and negative distances are invalid.
  • If the default 50-pixel distance includes unintended elements, use a smaller positive distance or a more specific candidate locator.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server, not a Selenium relative-locator replacement. If you need a screenshot of a page rather than an automated element lookup, one GET request can return an image or PDF. Its capture can accept cookie or consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets before the shot; those steps can be turned off. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing status. AI agents can use its MCP server tools, including take_screenshot, get_page_info, and capture_pdf.

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

See the ScreenshotNeo API documentation for request options. The free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000. Sign up for ScreenshotNeo’s free plan.

Frequently Asked Questions

Does a relative locator replace Selenium’s ordinary locators?

No. It uses an ordinary candidate locator together with a spatial relationship to a reference element.

Can I use a relative locator with an already located element?

Yes. In Python, the reference can be a WebElement, as in locate_with(By.CSS_SELECTOR, "p").above(element).

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.

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

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. 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
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair 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.