announcement-icon

Black Friday Special: Get up to 75% off setup fees when you confirm a project by Dec 31. Start in Q1 2027.

search-close-icon

Search here

Can't find what you are looking for?

Feel free to get in touch with us for more information about our products and services.

Tutorial: Building a Web Scraper that Handles Dynamic Content, Infinite Scroll, and AJAX Loading

Last updated: November 25, 2026

To scrape a page that loads content with JavaScript, infinite scroll or AJAX, either render it in a headless browser such as Playwright and scroll until no new items appear, or find the JSON request the page makes in the browser’s Network tab and call it directly. This tutorial shows both approaches in Python and when each fits.

Dynamic content is page content built or fetched by JavaScript after the first HTML loads, so it is missing from a plain HTTP response; infinite scroll and AJAX loading are two common ways this happens.

To scrape a page that loads content with JavaScript, infinite scroll or AJAX, either render it in a headless browser such as Playwright, or find the JSON request the page makes and call that endpoint directly. This tutorial shows both approaches, with code that was run against a local test page that loads items as you scroll. Only scrape pages whose terms allow it, and prefer an official API where one exists.

What Are Dynamic Content, Infinite Scroll and AJAX Loading?

Dynamic Content

  • Content rendered by JavaScript instead of static HTML
  • Requires browser rendering or API inspection to extract

Infinite Scroll

  • Pages load more content as the user scrolls down
  • Content is not present in the initial HTML

AJAX Loading

  • Content fetched asynchronously from APIs in the background
  • Requires capturing network requests or rendering scripts

Which Tools Do You Need to Scrape Dynamic Websites?

3. Step-by-Step Scraper Development

Step 1: Set Up Browser Automation

Install the libraries and the Chromium browser used by Playwright:

pip install playwright beautifulsoup4 pandas requests
playwright install chromium

Headless browsers render JavaScript without opening a window. The full script below uses Playwright’s synchronous API.

Step 2: How Do You Scrape an Infinite Scroll Page?

Dynamic pages often load additional content as you scroll. Instead of a fixed sleep and an open-ended loop, scroll, wait, and stop when the item count stops growing. A maximum scroll count (MAX_SCROLLS) is a safety stop so the loop can never run forever. In the script below, steps 1 to 5 are combined so you can run it end to end.

# CONFIG
URL = "https://example.com/products"  # page to scrape (use a page whose terms allow it)
MAX_SCROLLS = 50                      # safety stop: never scroll more than this many times
SCROLL_WAIT_MS = 2000                 # wait for new items after each scroll
ITEM_SELECTOR = "div.product"         # CSS selector for one item
OUTPUT_CSV = "products.csv"           # where to write the result

# LOGIC
import pandas as pd
from bs4 import BeautifulSoup
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()
    page.goto(URL)
    page.wait_for_selector(ITEM_SELECTOR)

    last_count = 0
    for _ in range(MAX_SCROLLS):
        page.evaluate("window.scrollTo(0, document.body.scrollHeight)")
        page.wait_for_timeout(SCROLL_WAIT_MS)
        count = page.locator(ITEM_SELECTOR).count()
        if count == last_count:  # no new items appeared: stop
            break
        last_count = count

    html = page.content()
    browser.close()

soup = BeautifulSoup(html, "html.parser")
rows = []
for item in soup.select(ITEM_SELECTOR):
    rows.append({
        "name": item.find("h2").get_text(strip=True),
        "price": item.find("span", class_="price").get_text(strip=True),
    })

df = pd.DataFrame(rows)
df.to_csv(OUTPUT_CSV, index=False)

If the item count stops growing, the loop ends. If it would never stop, MAX_SCROLLS ends it. Each row takes its name and price from the same item, so every row holds its own values.

Step 3: How Do You Capture AJAX Calls?

Some websites load content via API endpoints:

  1. Open browser DevTools, go to the Network tab, and filter for XHR or Fetch requests.
  2. Identify requests that return JSON.
  3. Use Requests or HTTPX to fetch the JSON directly, if the site’s terms and any API rules allow it.
import requests

response = requests.get("https://example.com/api/data", params={"page": 1}, timeout=10)
response.raise_for_status()
data = response.json()

Direct API calls are often faster and more reliable than parsing rendered HTML when you can use them.

Step 4: Parse Rendered Content

Once content is rendered or fetched, parse it with Beautiful Soup, as in the script above. soup.select(ITEM_SELECTOR) returns one element per item, and each row is built inside the loop from that item’s own fields.

Step 5: Store and Structure Data

The script builds a list of row dictionaries, one per item, and writes them with pandas. Check the result: the row count should match the number of items on the page, and names should not repeat unless the site repeats them.

Step 6: Handle Errors and Blocks

  • Implement retries and error logging.
  • Monitor scraper performance.
  • If a site blocks or rate-limits you, treat that as a signal to slow down, check the site’s terms and robots.txt (RFC 9309), and look for an official API or licence.

Step 7: Automate Scheduling

Recurring scraping needs orchestration:

  • Airflow or Prefect can schedule extraction pipelines.
  • Add retries, logging, and alerts.
  • Deliver results via API or cloud storage.

Which approach should you use: browser rendering or a direct API call?

SituationApproachWhy
Content appears only after JavaScript runsHeadless browser such as PlaywrightThe data is not in the first HTML response
Network tab shows a JSON request carrying the itemsCall that endpoint directlyFaster and more reliable than parsing rendered HTML when possible
Load more buttonClick, then wait for the network responseTies the script to when data arrives
Infinite scrollScroll until height or item count stops growingAdd a maximum scroll count as a safety stop

4. What Are the Best Practices for Scraping Dynamic Sites?

  1. Respect website terms of service and robots.txt.
  2. Use headless browsers only where the content needs rendering.
  3. Optimize scraping frequency to avoid overloading servers.
  4. Validate and clean data before storage.
  5. Monitor for changes in page layout or extraction failures.

5. Illustrative Scenario

This scenario is illustrative, not a customer story. A team wants to track many product listings on sites with infinite scroll and AJAX content. A pipeline could use a headless browser for scrolling, capture the underlying JSON endpoints where terms allow, clean and validate the data, and deliver it on a schedule to an analytics dashboard.

Conclusion

Scraping dynamic websites means handling JavaScript-rendered content, infinite scroll, and AJAX. With tools such as Playwright, Selenium, and Requests plus a scheduled pipeline, teams can collect this data consistently. If you would rather not maintain the pipeline, Grepsr offers managed extraction; scope is agreed per project and each source is reviewed against its terms before collection (see the Trust Center). Grepsr’s pricing page lists a Starter Pack from $100, priced on data records, at the time of this review (November 2026).

Related reading: How to Scrape JavaScript-Heavy Websites Without Getting Blocked (2026 Guide); How to Scrape Infinite Scroll and Paginated Websites Successfully; How to Handle Websites with Dynamic Content (JavaScript, AJAX): A Complete Guide for Businesses; Dynamic Content Scraping: How to Extract JavaScript and AJAX Data Reliably; Scraping Dynamic Websites at Scale: Why It Breaks and How Enterprises Fix It; Why Headless Browsers Solve One Problem and Create Three Others; Selenium and Playwright Made Easy for Enterprise-Grade Scraping; Selenium or Grepsr: How to Scrape JavaScript Websites Without Hassle.

Frequently Asked Questions

What is the difference between scraping rendered HTML and calling an API directly?

Rendered scraping loads the page in a headless browser, lets JavaScript run, then parses the resulting HTML. Direct calls skip the page and request the JSON endpoint the page uses behind the scenes. The post says direct API calls are faster and more reliable than parsing rendered HTML when they are possible, so check the Network tab first.

How do you find the request behind an AJAX-loaded list?

Open the browser’s developer tools, go to the Network tab, filter by XHR or fetch, and reload or scroll the page. Look for a request that returns JSON containing the items you see. Playwright can also track every request a page makes, including XHR and fetch calls, so you can capture the same endpoint inside your script.

Why use a network wait instead of a fixed sleep after scrolling?

A fixed pause is a guess: too short and you read the page before new items arrive, too long and every run is slower. Playwright offers expect_response, which waits for a matching network response after an action such as a click. Waiting on the response ties your script to when the data actually arrives.

How do you stop an infinite scroll loop from running forever?

Combine stop rules. End the loop when the page height or item count stops growing, and also set a maximum number of scrolls or a time limit so a page that never stops loading cannot hang the job. Log the final item count so a run that stopped early can be spotted and compared with earlier runs.

When is Selenium a better choice than Playwright for dynamic pages?

Both automate a real browser and can render JavaScript, and the post lists them as alternatives. The choice is usually about your team’s existing code and tooling. Grepsr’s comparison of Selenium and managed scraping explains where in-house browser automation becomes costly, which helps when deciding whether to run these scripts yourself.

Web data made accessible. At scale.
Tell us what you need. Let us ease your data sourcing pains!

Last reviewed: November 25, 2026.

arrow-up-icon