How to scroll to the bottom of the page with Selenium?

When web scraping with Selenium we might encounter pages that require scrolling to the bottom to load more content. This is a common pattern for infinite scrolling pages.

To scroll our Selenium browser custom javascript function window.scrollTo(x, y) can be used. This function scrolls the page to the specified coordinates.

So, if we need to scroll to the very bottom of the page we can use a while loop to continuously scroll until the bottom is reached.
Let's take a look at an example by scraping web-scraping.dev/testimonials:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

driver = webdriver.Chrome()
driver.get("https://web-scraping.dev/testimonials/")

prev_height = -1
max_scrolls = 100
scroll_count = 0

while scroll_count < max_scrolls:
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(1)  # give some time for new results to load
    new_height = driver.execute_script("return document.body.scrollHeight")
    if new_height == prev_height:
        break
    prev_height = new_height
    scroll_count += 1

# Collect all loaded data
elements = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.CLASS_NAME, "testimonial")))

results = []
for element in elements:
    text = element.find_element(By.CLASS_NAME, "text").get_attribute('innerHTML')
    results.append(text)

print(f"scraped: {len(results)} results!")

driver.quit()

Above, we're scraping an endless paging example from the web-scraping.dev website.
We start a while loop and keep scrolling to the bottom until the browser's vertical size stops changing.
Then, once the bottom is reached we can start parsing the content.

Question tagged: Selenium

Related Posts

How to Scrape With Headless Firefox

Discover how to use headless Firefox with Selenium, Playwright, and Puppeteer for web scraping, including practical examples for each library.

Selenium Wire Tutorial: Intercept Background Requests

In this guide, we'll explore web scraping with Selenium Wire. We'll define what it is, how to install it, and how to use it to inspect and manipulate background requests.

Web Scraping Dynamic Web Pages With Scrapy Selenium

Learn how to scrape dynamic web pages with Scrapy Selenium. You will also learn how to use Scrapy Selenium for common scraping use cases, such as waiting for elements, clicking buttons and scrolling.