SeleniumHQ/selenium · error · WebDriverException

Element or locator must be given when calling to_right_of me

Error message

Element or locator must be given when calling to_right_of method

What it means

RelativeBy.to_right_of requires a non-null element_or_locator; a falsy value raises WebDriverException naming the 'to_right_of' method.

Source

Thrown at py/selenium/webdriver/support/relative_locator.py:201

    def to_right_of(self, element_or_locator: WebElement | dict | None = None) -> "RelativeBy":
        """Add a filter to look for elements right of.

        Args:
            element_or_locator: Element to look right of

        Returns:
            RelativeBy

        Raises:
            WebDriverException: If `element_or_locator` is None.

        Example:
            >>> left = driver.find_element(By.ID, "left")
            >>> elements = driver.find_elements(locate_with(By.CSS_SELECTOR, "p").to_right_of(left))
        """
        if not element_or_locator:
            raise WebDriverException("Element or locator must be given when calling to_right_of method")

        self.filters.append({"kind": "right", "args": [element_or_locator]})
        return self

    @overload
    def straight_above(self, element_or_locator: WebElement | LocatorType) -> "RelativeBy": ...

    @overload
    def straight_above(self, element_or_locator: None = None) -> "NoReturn": ...

    def straight_above(self, element_or_locator: WebElement | LocatorType | None = None) -> "RelativeBy":
        """Add a filter to look for elements above.

        Args:
            element_or_locator: Element to look above
        """
        if not element_or_locator:
            raise WebDriverException("Element or locator must be given when calling above method")

View on GitHub (pinned to aa36b38e69)

Solutions

  1. Resolve and verify the anchor before chaining .to_right_of().
  2. Guard the value before calling.
  3. Use find_element for anchors so misses surface early.

Example fix

# before
left = maybe_find()
elements = driver.find_elements(locate_with(By.CSS_SELECTOR, "p").to_right_of(left))

# after
left = driver.find_element(By.ID, "left")
elements = driver.find_elements(locate_with(By.CSS_SELECTOR, "p").to_right_of(left))
Defensive patterns

Strategy: type-guard

Validate before calling

if not element_or_locator:
    raise ValueError("anchor required before .to_right_of()")

Type guard

from selenium.webdriver.remote.webelement import WebElement
def is_anchor(v) -> bool:
    return isinstance(v, WebElement) or (isinstance(v, dict) and v)

Prevention

When it happens

Trigger: Chaining .to_right_of(None) or passing an unresolved/empty locator.

Common situations: Piping a not-found anchor into .to_right_of().

Related errors


AI-assisted analysis of SeleniumHQ/selenium@aa36b38e69 (2026-08-14). Data as JSON: /api/errors/8d614776630b01a2. Report an issue: GitHub.