Near

Introduction

Selenium 4 introduced Relative Locators, a powerful feature that allows automation engineers to locate web elements based on their position relative to other elements on a webpage. Instead of depending entirely on attributes such as ID, Name, or XPath expressions, Relative Locators use an element’s visual position to identify related elements.

The near() Relative Locator is used to locate an element that appears close to another known element on the webpage within a specified pixel distance. This approach is particularly useful when elements do not contain unique attributes but are consistently positioned near one another.

In this tutorial, you’ll learn what the near() Relative Locator is, why it is used, its syntax, practical examples, real-world use cases, common mistakes, and best practices.


What is the Near Relative Locator?

The near() Relative Locator identifies a web element that is positioned close to another known element on the webpage.

Instead of locating an element directly, Selenium first identifies a reference element and then searches for matching elements that appear within a specified pixel distance from it.

For example, consider the following webpage layout:

---------------------------------
| Password                      |
| [______________]              |
|                               |
---------------------------------

The Password textbox appears near its corresponding Password label.

Selenium can use the Password label as the reference element and locate the Password textbox using the near() Relative Locator.


Why Use the Near Relative Locator?

The near() Relative Locator is useful because it:

  • Locates elements using their visual proximity.

  • Reduces dependency on complex XPath expressions.

  • Improves locator readability.

  • Supports modern webpage layouts.

  • Improves framework maintainability.

  • Is widely used in Selenium 4 automation frameworks.


Syntax

driver.find_element(
    locate_with(
        By.TAG_NAME,
        "input"
    ).near(
        reference_element,
        pixel_distance
    )
)

Where:

  • locate_with() → Creates a Relative Locator.

  • By.TAG_NAME → Defines the element type.

  • near() → Locates elements positioned near the reference element.

  • reference_element → Previously located web element used as the reference point.

  • pixel_distance → Maximum distance (in pixels) within which Selenium searches for the element.


Example

The Login page contains a Password label and its corresponding Password textbox positioned close to one another. Selenium first locates the Password label and then identifies the Password textbox positioned nearby.

The Selenium code is:

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


# Topic: 14. Selenium 4 Relative Locators - Near
# Practice site: https://the-internet.herokuapp.com/login
# Run: pytest -s 14_examples/test_05_near.py
#
# The near() relative locator finds an element close to a reference element
# within a specified pixel distance.


def test_relative_locator_near():
    driver = webdriver.Chrome()

    try:
        driver.get("https://the-internet.herokuapp.com/login")

        password_label = driver.find_element(
            By.CSS_SELECTOR,
            "label[for='password']"
        )

        password_field = driver.find_element(
            locate_with(
                By.TAG_NAME,
                "input"
            ).near(
                password_label,
                50
            )
        )

        assert password_field.get_attribute(
            "id"
        ) == "password"

    finally:
        driver.quit()

Output

The Password textbox is
located successfully using
the near() Relative Locator
with the Password label as
the reference element.

Understanding the Code

Import the Required Classes

from selenium.webdriver.common.by import By

from selenium.webdriver.support.relative_locator import (
    locate_with
)

Imports Selenium’s locator strategies and Relative Locator functionality.

Open the Login Page

driver.get(
    "https://the-internet.herokuapp.com/login"
)

Launches the Selenium practice website.

Locate the Password Label

driver.find_element(
    By.CSS_SELECTOR,
    "label[for='password']"
)

Locates the Password label that will be used as the reference element.

Locate the Password Textbox

driver.find_element(
    locate_with(
        By.TAG_NAME,
        "input"
    ).near(
        password_label,
        50
    )
)

Searches for an <input> element positioned within 50 pixels of the Password label.

Validate the Element

assert password_field.get_attribute(
    "id"
) == "password"

Verifies that Selenium successfully located the Password textbox.


How the Near Relative Locator Works

          Python Script
                 │
                 ▼
          Locate Reference Element
                 │
                 ▼
             Password Label
                 │
                 ▼
              Apply near()
                 │
                 ▼
      Search Within Pixel Distance
                 │
                 ▼
          Locate Nearby Element
                 │
                 ▼
             Perform Validation

Practical Example

Suppose you’re automating a Registration page.

The Email textbox appears immediately beside its corresponding label, but neither element contains stable HTML attributes across different environments.

Instead of creating complex XPath expressions, Selenium can locate the label first and then use the near() Relative Locator to identify the Email textbox reliably.

This significantly improves locator readability and maintainability.


Automation Testing Example

Consider an online banking application.

The Login page contains labels and textboxes that are consistently positioned close to one another. During future UI enhancements, developers may modify HTML attributes while preserving the overall page layout.

Selenium uses Relative Locators to identify nearby elements based upon their visual proximity, reducing automation failures during regression testing across environments.


Real-World Example

Automation engineers frequently use the near() Relative Locator while working with:

  • Banking applications.

  • E-Commerce websites.

  • Healthcare portals.

  • CRM systems.

  • ERP applications.

  • SaaS products.

  • Enterprise web applications.

  • Registration forms.

  • Dynamic dashboards.

Relative Locators are particularly useful whenever elements maintain stable visual relationships and remain positioned close to one another.


Advantages of the Near Relative Locator

  • Improves locator readability.

  • Reduces dependency on complex XPath expressions.

  • Supports dynamic webpage layouts.

  • Improves framework maintainability.

  • Produces clean and reusable automation scripts.

  • Widely used in Selenium 4 automation frameworks.


Limitations of the Near Relative Locator

  • Depends upon the visual positioning of elements.

  • Pixel distance values may require adjustments after UI changes.

  • Multiple nearby elements may require additional filtering.

  • Not suitable for every webpage design.


Common Mistakes Beginners Make

Using Incorrect Pixel Distances

Incorrect

password_field = driver.find_element(
    locate_with(
        By.TAG_NAME,
        "input"
    ).near(
        password_label,
        5
    )
)

Correct

password_field = driver.find_element(
    locate_with(
        By.TAG_NAME,
        "input"
    ).near(
        password_label,
        50
    )
)

Always use an appropriate pixel distance based on the webpage layout.

Ignoring Page Layout Changes

The near() Relative Locator depends upon the proximity between elements. Significant UI changes may require updating the specified pixel distance.

Using Relative Locators Unnecessarily

If a stable ID or Name attribute uniquely identifies an element, prefer simpler locator strategies whenever appropriate.


Best Practices

  • Use stable reference elements whenever possible.

  • Choose appropriate pixel distances for nearby elements.

  • Verify webpage layouts using browser Developer Tools.

  • Keep automation scripts simple and readable.

  • Use Relative Locators alongside traditional locator strategies when appropriate.

  • Write maintainable and reusable locators within automation frameworks.


Conclusion

The near() Relative Locator introduced in Selenium 4 provides a powerful and readable way to locate web elements based upon their proximity to other elements. It significantly improves locator flexibility when working with modern web applications that contain dynamic or frequently changing HTML attributes.

Understanding the near() Relative Locator completes the foundation of Selenium 4 Relative Locators and provides automation engineers with additional flexibility when designing scalable automation frameworks.


Frequently Asked Questions (FAQs)

What is the Near Relative Locator?

The near() Relative Locator identifies an element that is positioned close to another known element within a specified pixel distance.

What is the syntax for the Near Relative Locator?

driver.find_element(
    locate_with(
        By.TAG_NAME,
        "input"
    ).near(
        reference_element,
        pixel_distance
    )
)

Why is the Near Relative Locator useful?

It improves locator readability and allows Selenium to locate elements based upon their visual proximity to other elements.

Can Relative Locators replace XPath completely?

No.

Relative Locators complement traditional locator strategies such as ID, CSS Selectors, and XPath. The most suitable locator should always be chosen based upon the application’s requirements.

When should I use the Near Relative Locator?

Use it whenever elements maintain stable visual relationships and are positioned close to one another but do not contain reliable or unique HTML attributes.


Key Takeaways

  • The near() Relative Locator identifies elements positioned close to a reference element.

  • It allows Selenium to search within a specified pixel distance.

  • Relative Locators improve locator readability and maintainability.

  • Use stable reference elements and appropriate pixel distances whenever possible.

  • Relative Locators are widely used in Selenium 4 automation frameworks.

  • The near() Relative Locator is particularly useful when automating modern and dynamic web applications.