SeleniumHQ/selenium · error · WebDriverException
Distance must be positive
Error message
Distance must be positive
What it means
`RelativeBy.near()` validates that its `distance` argument (pixels, default 50) is strictly positive. A value of 0 or negative raises WebDriverException because a non-positive radius would never match any neighbouring element.
Source
Thrown at py/selenium/webdriver/support/relative_locator.py:305
Args:
element_or_locator: Element to look near by the element or within a distance
distance: Distance in pixel
Returns:
RelativeBy
Raises:
WebDriverException: If `element_or_locator` is None
WebDriverException: If `distance` is less than or equal to 0.
Example:
>>> near = driver.find_element(By.ID, "near")
>>> elements = driver.find_elements(locate_with(By.CSS_SELECTOR, "p").near(near, 50))
"""
if not element_or_locator:
raise WebDriverException("Element or locator must be given when calling near method")
if distance <= 0:
raise WebDriverException("Distance must be positive")
self.filters.append({"kind": "near", "args": [element_or_locator, distance]})
return self
def to_dict(self) -> dict:
"""Create a dict to be passed to the driver for element searching."""
return {
"relative": {
"root": self.root,
"filters": self.filters,
}
}
View on GitHub (pinned to aa36b38e69)
Solutions
- Pass a positive integer: `locator.near(anchor, distance=50)`
- If distance is computed, clamp it to a positive minimum: `distance = max(distance, 1)`
- Omit the argument entirely to use the default of 50 pixels
Example fix
// before loc = locate_with(By.CSS_SELECTOR, "p").near(near, 0) // after loc = locate_with(By.CSS_SELECTOR, "p").near(near, 50)
Defensive patterns
Strategy: validation
Validate before calling
distance = max(distance, 1) # clamp to positive loc = locate_with(By.CSS_SELECTOR, "p").near(anchor, distance)
Type guard
def is_positive_distance(d) -> bool:
return isinstance(d, (int, float)) and d > 0 Prevention
- Omit distance to use the safe default of 50
- Clamp computed distances to a positive minimum before passing
- Never pass 0 or negative distances intending 'closest'
When it happens
Trigger: Calling `locate_with(...).near(anchor, distance=0)`, a negative distance, or passing a computed distance that evaluated to <= 0 (e.g. from a layout measurement that returned 0).
Common situations: Passing 0 to mean 'as close as possible'; deriving distance from a possibly-zero element rect calculation; off-by-one when converting units.
Related errors
- Element or locator must be given when calling near method
- 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_left_of met
AI-assisted analysis of SeleniumHQ/selenium@aa36b38e69 (2026-08-14).
Data as JSON: /api/errors/ba5a141ed2854e9f.
Report an issue: GitHub.