Skip to content

Commit 3b5ac10

Browse files
committed
Optimize the "find_visible_elements(selector)" method
1 parent ef0aedc commit 3b5ac10

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

seleniumbase/fixtures/base_case.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2162,9 +2162,9 @@ def find_visible_elements(self, selector, by="css selector", limit=0):
21622162
selector, by = self.__recalculate_selector(selector, by)
21632163
self.wait_for_ready_state_complete()
21642164
time.sleep(0.05)
2165-
v_elems = page_actions.find_visible_elements(self.driver, selector, by)
2166-
if limit and limit > 0 and len(v_elems) > limit:
2167-
v_elems = v_elems[:limit]
2165+
v_elems = page_actions.find_visible_elements(
2166+
self.driver, selector, by, limit
2167+
)
21682168
return v_elems
21692169

21702170
def click_visible_elements(

seleniumbase/fixtures/page_actions.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1251,26 +1251,40 @@ def wait_for_attribute_not_present(
12511251
timeout_exception(Exception, message)
12521252

12531253

1254-
def find_visible_elements(driver, selector, by="css selector"):
1254+
def find_visible_elements(driver, selector, by="css selector", limit=0):
12551255
"""
12561256
Finds all WebElements that match a selector and are visible.
1257-
Similar to webdriver.find_elements.
1257+
Similar to webdriver.find_elements().
1258+
If "limit" is set and > 0, will only return that many elements.
12581259
@Params
12591260
driver - the webdriver object (required)
12601261
selector - the locator for identifying the page element (required)
12611262
by - the type of selector being used (Default: "css selector")
1263+
limit - the maximum number of elements to return if > 0.
12621264
"""
12631265
elements = driver.find_elements(by=by, value=selector)
1266+
if limit and limit > 0 and len(elements) > limit:
1267+
elements = elements[:limit]
12641268
try:
12651269
v_elems = [element for element in elements if element.is_displayed()]
12661270
return v_elems
12671271
except (StaleElementReferenceException, ElementNotInteractableException):
12681272
time.sleep(0.1)
12691273
elements = driver.find_elements(by=by, value=selector)
1274+
extra_elements = []
1275+
if limit and limit > 0 and len(elements) > limit:
1276+
elements = elements[:limit]
1277+
extra_elements = elements[limit:]
12701278
v_elems = []
12711279
for element in elements:
12721280
if element.is_displayed():
12731281
v_elems.append(element)
1282+
if extra_elements and limit and len(v_elems) < limit:
1283+
for element in extra_elements:
1284+
if element.is_displayed():
1285+
v_elems.append(element)
1286+
if len(v_elems) >= limit:
1287+
break
12741288
return v_elems
12751289

12761290

0 commit comments

Comments
 (0)