@@ -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