SeleniumHQ/selenium · error · WebDriverException
Element or locator must be given when calling to_left_of met
Error message
Element or locator must be given when calling to_left_of method
What it means
RelativeBy.to_left_of requires a non-null element_or_locator; a falsy value raises WebDriverException naming the 'to_left_of' method.
Source
Thrown at py/selenium/webdriver/support/relative_locator.py:173
def to_left_of(self, element_or_locator: WebElement | dict | None = None) -> "RelativeBy":
"""Add a filter to look for elements to the left of.
Args:
element_or_locator: Element to look to the left of
Returns:
RelativeBy
Raises:
WebDriverException: If `element_or_locator` is None.
Example:
>>> right = driver.find_element(By.ID, "right")
>>> elements = driver.find_elements(locate_with(By.CSS_SELECTOR, "p").to_left_of(right))
"""
if not element_or_locator:
raise WebDriverException("Element or locator must be given when calling to_left_of method")
self.filters.append({"kind": "left", "args": [element_or_locator]})
return self
@overload
def to_right_of(self, element_or_locator: WebElement | LocatorType) -> "RelativeBy": ...
@overload
def to_right_of(self, element_or_locator: None = None) -> "NoReturn": ...
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:
RelativeByView on GitHub (pinned to aa36b38e69)
Solutions
- Resolve and verify the anchor before chaining .to_left_of().
- Guard the value before calling.
- Use find_element for anchors so misses surface early.
Example fix
# before right = maybe_find() elements = driver.find_elements(locate_with(By.CSS_SELECTOR, "p").to_left_of(right)) # after right = driver.find_element(By.ID, "right") elements = driver.find_elements(locate_with(By.CSS_SELECTOR, "p").to_left_of(right))
Defensive patterns
Strategy: type-guard
Validate before calling
if not element_or_locator:
raise ValueError("anchor required before .to_left_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
- Assert the anchor is non-None before chaining direction methods.
- Resolve anchors with find_element, not optional lookups.
When it happens
Trigger: Chaining .to_left_of(None) or passing an unresolved/empty locator.
Common situations: Piping a not-found anchor into .to_left_of().
Related errors
- tag_name can not be null
- Element or locator must be given when calling above method
- Element or locator must be given when calling below method
- Element or locator must be given when calling to_right_of me
- Element or locator must be given when calling near method
AI-assisted analysis of SeleniumHQ/selenium@aa36b38e69 (2026-08-14).
Data as JSON: /api/errors/a06308f89ac78c0f.
Report an issue: GitHub.