Skip to content

Commit c188fe8

Browse files
raise NoSuchElementException for relative failures instead of IndexError (#10078)
Co-authored-by: David Burns <[email protected]>
1 parent fc66324 commit c188fe8

2 files changed

Lines changed: 16 additions & 3 deletions

File tree

py/selenium/webdriver/remote/webdriver.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,8 @@
4545
from selenium.common.exceptions import (InvalidArgumentException,
4646
JavascriptException,
4747
WebDriverException,
48-
NoSuchCookieException)
48+
NoSuchCookieException,
49+
NoSuchElementException)
4950
from selenium.webdriver.common.by import By
5051
from selenium.webdriver.common.options import BaseOptions
5152
from selenium.webdriver.common.print_page_options import PrintOptions
@@ -1227,7 +1228,10 @@ def find_element(self, by=By.ID, value=None) -> WebElement:
12271228
:rtype: WebElement
12281229
"""
12291230
if isinstance(by, RelativeBy):
1230-
return self.find_elements(by=by, value=value)[0]
1231+
elements = self.find_elements(by=by, value=value)
1232+
if not elements:
1233+
raise NoSuchElementException(f"Cannot locate relative element with: {by.root}")
1234+
return elements[0]
12311235

12321236
if by == By.ID:
12331237
by = By.CSS_SELECTOR

py/test/selenium/webdriver/support/relative_by_tests.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,10 @@
1414
# KIND, either express or implied. See the License for the
1515
# specific language governing permissions and limitations
1616
# under the License.
17-
17+
from selenium.common.exceptions import NoSuchElementException
1818
from selenium.webdriver.common.by import By
1919
from selenium.webdriver.support.relative_locator import with_tag_name, locate_with
20+
import pytest
2021

2122

2223
def test_should_be_able_to_find_first_one(driver, pages):
@@ -67,3 +68,11 @@ def test_should_be_able_to_use_xpath(driver, pages):
6768

6869
ids = [el.get_attribute('id') for el in elements]
6970
assert "fourth" in ids
71+
72+
73+
def test_no_such_element_is_raised_rather_than_index_error(driver, pages):
74+
pages.load("relative_locators.html")
75+
with pytest.raises(NoSuchElementException) as exc:
76+
anchor = driver.find_element(By.ID, "second")
77+
driver.find_element(locate_with(By.ID, "nonexistentid").above(anchor))
78+
assert exc.value.msg == "Cannot locate relative element with: {'id': 'nonexistentid'}"

0 commit comments

Comments
 (0)