Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

How to Crawl JavaScript Rendered Websites

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

JavaScript-rendered websites load most of their content dynamically after the initial HTML arrives, so a basic HTTP crawler only sees an empty shell. This guide shows you how to use a headless browser to execute the JavaScript, wait for the content to appear, and then extract the data you need. You'll learn a practical, step-by-step approach using Python and Playwright, which is well-suited for this task.

What You'll Need

  • Python 3.7 or later installed on your system.
  • Basic familiarity with the command line (terminal or command prompt).
  • A code editor or even a simple text editor.
  • An understanding of HTML and CSS selectors (like div.product-title).
  • An internet connection to install packages and access the target site.

Step-by-Step

  1. Set up a project folder. Create a new directory for your crawler and navigate into it in your terminal. This keeps everything organized.
  2. Install Playwright. Run pip install playwright in your terminal. Then, run playwright install to download the browser binaries (Chromium, Firefox, or WebKit). Chromium is a solid default.
  3. Write a basic script. Create a Python file, e.g., crawler.py. Start by importing Playwright and launching a browser:
  4. 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-site.com')
        print(page.title())
        browser.close()
  5. Wait for the content to load. Simply using goto() may not be enough. Use page.wait_for_selector() to wait for a specific element that you know appears only after JavaScript runs. For example:
  6. page.wait_for_selector('div.product-list')
  7. Extract data. Use page.query_selector_all() to get a list of elements, then loop through them to pull text or attributes. Here's a simple example that grabs all product names:
  8. products = page.query_selector_all('h2.product-name')
    for product in products:
        print(product.inner_text())
  9. Handle infinite scroll or “Load More” buttons. Many sites load content as you scroll. Automate scrolling with page.mouse.wheel() or page.evaluate() to scroll to the bottom, then wait for new content. Alternatively, click a “Load More” button if present.
  10. Deal with pagination. If the site uses pagination, find the “Next” button and click it. Loop until the button is no longer visible. Always check that you're not accidentally scraping the same page twice.
  11. Save your results. Store the extracted data in a structured format like CSV or JSON. Python's built-in csv or json modules work well. Write the data as you go to avoid losing progress if the script crashes.
  12. Add politeness and error handling. Include random delays between requests (e.g., time.sleep(2)) to avoid hammering the server. Wrap your code in try/except blocks to handle timeouts or missing elements gracefully.
  13. Run and test. Execute your script with python crawler.py. Start with a small number of pages to verify it works, then scale up.

Common Mistakes

  • Not waiting long enough. JavaScript can take time to fetch data from APIs. If you don't wait for a specific selector, you'll get empty results. Always use wait_for_selector().
  • Using the wrong selector. CSS selectors can change frequently. Inspect the element in your browser's developer tools to confirm the exact selector. Avoid overly broad selectors that might match unrelated elements.
  • Ignoring network requests. Some sites load data via XHR/fetch requests. You might need to intercept those responses. Playwright can listen to network events, but that's an advanced topic.
  • Blocked by anti-bot measures. Sites may use CAPTCHAs or block headless browsers. Try using a real user-agent string, or run in headed mode (headless=False) to see what's happening.
  • Scraping too fast. Sending requests too quickly can get your IP banned. Always add delays and respect the site's robots.txt.

Tips

  • Use a real browser profile. If you're having trouble with detection, launch with headless=False and a non-default user-agent. Some sites behave differently in headless mode.
  • Leverage Playwright's built-in waiting. The page.wait_for_selector() method is powerful. You can also use page.wait_for_load_state('networkidle') but be careful—it can be slow.
  • Take screenshots for debugging. Use page.screenshot(path='debug.png') to see what the browser sees when something goes wrong.
  • Structure your code. Write functions for each major step (e.g., load_page(), extract_data(), save_data()). This makes it easier to maintain and reuse.
  • Respect the website. Always check the site's terms of service and robots.txt. Scraping can be legal or illegal depending on the site and jurisdiction. When in doubt, ask for permission.

Troubleshooting

  • Getting empty results. This usually means the selector didn't match anything. Check if the content is inside an iframe. If so, you need to switch to the iframe context using page.frame_locator().
  • Timeout errors. Increase the timeout in wait_for_selector() (e.g., timeout=30000). Also, make sure the page actually loads—sometimes the server is slow or the URL is wrong.
  • Browser crashes. If Chromium crashes, try installing the latest version or using a different browser (Firefox or WebKit). Also, ensure your system meets the minimum requirements.
  • Site shows a CAPTCHA. This is a sign you're being detected. Try adding a random delay, using a real user-agent, or rotating IPs (if you have a proxy). If the site is aggressive, you might need to use a service like ScrapingBee or ScraperAPI, but that's beyond this guide.
  • JavaScript not executing. Some sites require certain permissions or have errors in their own scripts. Check the browser console for errors using page.on('console', lambda msg: print(msg.text)).
  • Memory leaks. If you're scraping many pages in a loop, close the page after each iteration (page.close()) to free memory. Also, consider using async version of Playwright for better performance.

Frequently Asked Questions

Can I use Selenium instead of Playwright?

Yes, Selenium is another popular option. Playwright is often faster and has a cleaner API, but Selenium works fine for most cases. The general approach is the same.

Is it legal to crawl JavaScript-rendered websites?

It depends on the website's terms of service and your local laws. Always check robots.txt and the site's terms. Public data is generally safer, but personal data may be protected by regulations like GDPR.

What if the site uses an API to load data?

You can often bypass rendering entirely by calling the API directly. Use your browser's developer tools to find the network requests, then replicate them with Python's requests library. This is more efficient and less likely to be blocked.

How do I handle infinite scroll?

Scroll to the bottom of the page, wait for new content to load, then scroll again. Repeat until no new content appears. Playwright's page.mouse.wheel() or page.evaluate('window.scrollTo(0, document.body.scrollHeight)') works well.

Can I crawl a site that requires login?

Yes, you can use Playwright to fill in login forms and maintain a session. However, you must have permission to access that content. Automating logins can violate terms of service, so proceed with caution.

How can I avoid being blocked?

Use realistic delays, rotate user-agents, and limit your request rate. Consider using a proxy service if you need to scrape at scale. Also, try to mimic human behavior by not clicking too fast and varying your actions.