Prompt
How do I scrape data from a website that loads content with JavaScript?
Latest observation
If a site loads content with JavaScript, a plain requests.get() often won’t be enough because the HTML you receive is just the shell, and the real data is fetched later by the browser.
Here are the main approaches, from simplest to most robust:
1) Check if the data comes from an API
This is usually the best option.
- Open the site in your browser
- Open DevTools → Network
- Filter by Fetch/XHR
- Reload the page
- Look for requests returning JSON or other structured data
If you find an API endpoint, you can often scrape that directly with requests or httpx:
import requests
url = "https://example.com/api/data"
headers = {
"User-Agent": "Mozilla/5.0"
}
response = requests.get(url, headers=headers)
data = response.json()
print(data)
2) Use a headless browser
If the content is rendered in the browser and there’s no easy API, use browser automation tools like:
- Playwright (recommended)
- Selenium
- Puppeteer (Node.js)
Example with Playwright in Python:
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.goto("https://example.com", wait_until="networkidle")
html = page.content()
print(html)
browser.close()
You can then parse the rendered HTML with BeautifulSoup:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, "html.parser")
print(soup.title.text)
3) Wait for dynamic elements
Sometimes the page loads content after a delay. You may need to wait for a selector to appear.
Playwright example:
page.goto("https://example.com")
page.wait_for_selector(".product-card")
cards = page.query_selector_all(".product-card")
4) Intercept network requests
If the page loads data via requests you can capture them in Playwright and reuse them without rendering the full page.
5) Beware of anti-bot protections
Some sites use:
- rate limiting
- CAPTCHAs
- login/session checks
- fingerprinting
Be polite:
- respect
robots.txt - use reasonable delays
- identify yourself if appropriate
- don’t overload the site
6) For very heavy pages, use the browser only to obtain data
A common workflow:
- Inspect browser network traffic
- Find the JSON endpoint
- Replicate it with
requests - Fall back to Playwright only if needed
Quick decision guide
- Data visible in Network/XHR as JSON → scrape the API
- Data only appears after JS renders → use Playwright/Selenium
- Data requires interaction → automate clicks/scrolls with Playwright
- Site blocks automation → use authenticated/session-aware scraping carefully
If you want, I can show you:
- how to inspect a specific site,
- a Playwright scraper template,
- or how to extract data from a page you link me.