Load Every Item on an Infinite Scroll Page
Scroll a lazy-loading feed until no new items arrive, with a hard cap, a growth-based wait instead of sleeps, and support for scrollable containers.
Problem
A product feed shows 20 items and loads 20 more each time you reach the bottom. You need all of them (to count, or to find one that is not on the first page). Scrolling once and sleeping two seconds is slow on fast runs and too short on slow ones, and a while (true) loop never ends if the feed is effectively infinite.
Solution
Loop: count items, scroll the last one into view, then wait for the count to grow. If it does not grow within a short timeout, you have reached the end. Cap the number of rounds so a truly endless feed cannot hang the test.
public static List<WebElement> loadAll(WebDriver driver, By item, int maxRounds) { JavascriptExecutor js = (JavascriptExecutor) driver; WebDriverWait growth = new WebDriverWait(driver, Duration.ofSeconds(5));
int count = driver.findElements(item).size(); for (int round = 0; round < maxRounds; round++) { List<WebElement> items = driver.findElements(item); if (items.isEmpty()) break; js.executeScript("arguments[0].scrollIntoView({block: 'end'});", items.get(items.size() - 1));
final int before = count; try { growth.until(d -> d.findElements(item).size() > before); } catch (TimeoutException end) { break; // no new items: end of feed } count = driver.findElements(item).size(); } return driver.findElements(item);}
List<WebElement> cards = loadAll(driver, By.cssSelector("[data-testid='product-card']"), 50);from selenium.common.exceptions import TimeoutException
def load_all(driver, item, max_rounds=50): growth = WebDriverWait(driver, 5) count = len(driver.find_elements(*item)) for _ in range(max_rounds): items = driver.find_elements(*item) if not items: break driver.execute_script("arguments[0].scrollIntoView({block: 'end'});", items[-1]) before = count try: growth.until(lambda d: len(d.find_elements(*item)) > before) except TimeoutException: break # end of feed count = len(driver.find_elements(*item)) return driver.find_elements(*item)
cards = load_all(driver, (By.CSS_SELECTOR, "[data-testid='product-card']"))async function loadAll(driver, item, maxRounds = 50) {let count = (await driver.findElements(item)).length;for (let round = 0; round < maxRounds; round++) { const items = await driver.findElements(item); if (items.length === 0) break; await driver.executeScript("arguments[0].scrollIntoView({block: 'end'});", items[items.length - 1]); const before = count; try { await driver.wait(async () => (await driver.findElements(item)).length > before, 5000); } catch (e) { if (e.name !== 'TimeoutError') throw e; break; // end of feed } count = (await driver.findElements(item)).length;}return driver.findElements(item);}
const cards = await loadAll(driver, By.css("[data-testid='product-card']"));public static IReadOnlyCollection<IWebElement> LoadAll(IWebDriver driver, By item, int maxRounds = 50){ var js = (IJavaScriptExecutor)driver; var growth = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
int count = driver.FindElements(item).Count; for (int round = 0; round < maxRounds; round++) { var items = driver.FindElements(item); if (items.Count == 0) break; js.ExecuteScript("arguments[0].scrollIntoView({block: 'end'});", items[items.Count - 1]);
int before = count; try { growth.Until(d => d.FindElements(item).Count > before); } catch (WebDriverTimeoutException) { break; } // end of feed count = driver.FindElements(item).Count; } return driver.FindElements(item);}
var cards = LoadAll(driver, By.CssSelector("[data-testid='product-card']"));Why It Works
Scrolling the last rendered item into view triggers the same IntersectionObserver or scroll listener a real user does, whether the feed lives in the window or in an inner scrollable container (the browser scrolls whichever ancestor is needed). Waiting on “count greater than before” returns the moment new items land, so fast pages are fast. The growth timeout doubles as end-of-feed detection, and maxRounds bounds the worst case.
Tuning
| Setting | Guidance |
|---|---|
| Growth timeout | Slightly longer than the slowest page fetch you see in CI. 3-5 s is typical. |
maxRounds | Expected total / page size, plus margin. For “find item X”, stop as soon as X appears instead. |
| Item locator | Target the card, not the loading skeleton; skeletons inflate the count and then disappear. |
Gotchas
- “Load more” buttons. Some feeds need a click at the bottom. Check for the button each round and click it instead of (or after) scrolling.
- Virtualised lists recycle nodes. If the DOM count stays roughly constant while you scroll, the list is virtualised and old items are removed. Collect identifiers (text or
data-id) into a set each round and stop when the set stops growing. - Finding one item. If you only need a specific item, check for it inside the loop and return early. Loading 2,000 items to find the 25th is wasted time.
- Stale elements. Items found in an earlier round may be re-rendered. Re-query at the end, as the code does, rather than keeping old references.
- Footer lazy content. Scrolling to the very bottom of the window can trigger unrelated lazy footers; scrolling the last item (not
window.scrollTo(0, document.body.scrollHeight)) avoids that.
Learn the theory
- Scrolling Scroll elements into view, scroll by an amount, use the W3C wheel actions, handle infinite scroll and sticky headers, and know when Selenium scrolls for you.
- Custom Wait Conditions Write your own expected conditions with lambdas and classes, wait for attribute and text changes, element counts, JavaScript state, network idleness via BiDi, and compose conditions cleanly.