Learn Scrapy Β· 9/13

Scraping Dynamic & JavaScript-Rendered Content

9 min read

πŸ•ΈοΈ Scrapy Guide: Scraping Dynamic & JavaScript-Rendered Content

Welcome, intrepid data wrangler! So far on your Scrapy journey, you've been expertly navigating the clean, well-paved highways of static HTML. But the web is a wild place, and much of its most valuable treasure is hidden behind the shimmering curtain of JavaScript.

The Problem: The Disappearing Content πŸ‘»

You've fired up a scrapy shell for a fancy new e-commerce site, ready to grab some product prices. You use view(response) and... wait a minute. The price, the user reviews, the "add to cart" button – they're all missing from the HTML file Scrapy received! Yet, you can see them perfectly fine in your Chrome or Firefox browser.

What gives? This is the classic challenge of dynamic content. The initial HTML the server sends is just a skeleton. Your browser then runs JavaScript code that fetches data from other places and populates the page after the initial load. Standard Scrapy, which is not a browser, only sees that initial skeleton and misses all the good stuff.

The Solution: Two Paths to Victory ✌️

Don't you worry, this is a common quest in the world of web scraping. We have two primary strategies to defeat this foe:

  1. Be a Spy (The Smart Way): Instead of trying to wrestle with the complex JavaScript, we can act like a detective. We'll watch how the browser gets its data and just copy it. This usually involves finding hidden API calls.
  2. Bring in the Muscle (The Brute-Force Way): When the spy method fails, we bring in the heavy artillery: a full-blown web browser that Scrapy can control. This will render the JavaScript for us, just like it does for a normal user.

Ready? Let's dive into the techniques.


1. Identifying API Calls via Browser Network Tab πŸ•΅οΈβ€β™€οΈ

This is the most important skill for scraping modern websites. It's faster, more reliable, and much more efficient than controlling a browser. Think of it as finding the secret back door to the kitchen instead of waiting in the long line at the front of the restaurant.

What's the Goal?

To find the hidden requests your browser makes to fetch data after the page loads. These requests often go to an Application Programming Interface (API), which returns data in a beautifully structured format like JSON.

Your Detective Toolkit: The Network Tab

Every modern browser comes with "Developer Tools." One of the most powerful tools in this kit is the Network tab. It logs every single request your browser makes – for images, for scripts, and most importantly, for data.

How to Use It (A Step-by-Step Guide):

  1. Navigate to the page you want to scrape in Chrome or Firefox.
  2. Open the Developer Tools. You can usually do this by right-clicking anywhere on the page and selecting "Inspect" or by pressing F12.
  3. Click on the "Network" tab.
  4. You might see a lot of noise. Let's filter it. Click on the Fetch/XHR button. (XHR stands for XMLHttpRequest, a fancy name for a way browsers fetch data). This filter shows you only the data requests we're interested in.
  5. Now, refresh the page or perform an action that loads new data (like scrolling or clicking a "Load More" button).
  6. Watch the requests that appear in the list! Click on them one by one. Look at the "Preview" or "Response" tabs on the right. Are you seeing the missing data you're looking for (like product prices or user comments) neatly organized in a JSON format? If so, BINGO! You've found the hidden API.

A typical view of the Network tab, your new best friend.


2. Scraping Hidden APIs and JSON Responses Directly 🎯

Once you've found the API endpoint, the hard part is over. Seriously. Scraping a JSON API is often much simpler than parsing messy HTML.

The Problem:

You've found the URL that the website uses to get its data (e.g., https://api.example.com/products?id=123). How do you make Scrapy go to that URL instead of the main website URL and then parse the JSON it gets back?

The Concept: Just Request the API URL!

It's that simple. In your spider, instead of starting with the website's public URL, you can directly target the API endpoint you discovered. Scrapy will fetch its content, and since that content is JSON, you can easily load it into a Python dictionary.

Example: A Simple API Spider

Let's imagine our detective work on an e-commerce site revealed that all product data comes from an API endpoint like https://api.fake-store.com/products/42.

python
import scrapy
import json

class ProductAPISpider(scrapy.Spider):
    name = 'product_api_spider'
    # We start directly with the API URL we found!
    start_urls = ['https://api.fake-store.com/products/42']

    def parse(self, response):
        # The response.body contains the JSON data.
        # We use Python's built-in json library to parse it.
        data = json.loads(response.body)

        # Now 'data' is a regular Python dictionary. We can access
        # its contents using keys, just like any other dictionary.
        yield {
            'id': data.get('id'),
            'name': data.get('title'),
            'price': data.get('price'),
            'category': data.get('category'),
            'description': data.get('description'),
            'image_url': data.get('image'),
        }

Look at that! No CSS selectors, no XPath, just clean, direct data access. This is why the API method is the industry standard and should always be your first choice.

Fun Fact: Many mobile apps are powered by the exact same APIs that websites use. By learning this technique, you're also taking your first step toward understanding how to gather data from mobile applications!


3. Integrating Scrapy with Playwright (scrapy-playwright) πŸ€–

Sometimes, you're out of luck. There's no clean API, and the website is a fortress of complex JavaScript that absolutely requires a real browser to render. This is where we bring in the muscle.

The Problem:

How do we make Scrapy, which is not a browser, behave like one? We need a way to control a real browser engine, let it run all the JavaScript, and then give the final, fully-rendered HTML to Scrapy for parsing.

The Solution: scrapy-playwright

Playwright is a powerful library made by Microsoft for browser automation. The scrapy-playwright library is the perfect bridge that allows Scrapy to use Playwright as its downloader. When a request is sent, instead of Scrapy fetching it, Playwright launches a headless browser (a browser without a visual interface), navigates to the URL, waits for the JavaScript to do its thing, and then hands the complete HTML over to your spider's parse method.

Installation and Setup (The Boring but Necessary Part)

Getting started with scrapy-playwright involves a few steps. Don't skip these!

  1. Install the library:

    bash
    pip install scrapy-playwright
  2. Install the browser binaries: Playwright needs to download the browsers it will control. This one-time command does that for you.

    bash
    playwright install
  3. Configure your Scrapy settings.py file: You need to tell Scrapy to use scrapy-playwright for handling downloads. Add these lines to your settings.py:

    python
    DOWNLOAD_HANDLERS = {
        "http": "scrapy_playwright.handler.ScrapyPlaywrightDownloadHandler",
        "httpses": "scrapy_playwright.handler.ScrapyPlaywrightDownloadHandler",
    }
    
    TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"

Example: A Playwright-Powered Spider

Now let's scrape a page that needs JavaScript to reveal the price.

python
import scrapy
# We can import PageMethod to perform actions on the page
from scrapy_playwright.page import PageMethod

class JsProductSpider(scrapy.Spider):
    name = 'js_product_spider'

    def start_requests(self):
        # We need to use scrapy.Request and not just a start_urls list
        yield scrapy.Request(
            url="http://quotes.toscrape.com/js/", # A site that uses JS to load quotes
            meta={
                "playwright": True,
                "playwright_include_page": True,
                # We can tell Playwright to wait for a specific element to appear
                "playwright_page_methods": [
                    PageMethod("wait_for_selector", "div.quote"),
                ],
            },
            errback=self.errback,
        )

    async def parse(self, response):
        # The 'playwright_include_page' gives us the page object
        page = response.meta["page"]
        await page.close() # It's a good practice to close the page

        for quote in response.css('div.quote'):
            yield {
                'text': quote.css('span.text::text').get(),
                'author': quote.css('small.author::text').get(),
            }

    async def errback(self, failure):
        page = failure.request.meta["page"]
        await page.close()

The key here is the meta dictionary in our scrapy.Request. By setting "playwright": True, we're telling Scrapy, "Hey, use the big guns for this one!". We can even pass instructions, like wait_for_selector, to ensure the browser doesn't give us the HTML until the content we need has actually loaded.


4. Strategies for Handling Infinite Scrolling Pages πŸ“œ

Ah, the infinite scroll. The bane of many a scraper. You scroll down, and more content just keeps appearing. How do you get to the bottom of it?

The Problem:

Your spider only gets the first batch of items. How do you trigger the loading of subsequent items and scrape them all without getting stuck in an... infinite loop?

Again, we have our two main strategies.

Strategy 1: Find the API (Always try this first!)

This is the most robust and efficient way.

  1. Open the Network Tab (Fetch/XHR).
  2. Start scrolling down the page.
  3. Observe! Do you see new requests appearing in the Network tab as you scroll? Often, you'll see a pattern in the URLs, like .../items?page=2, .../items?page=3, or .../posts?offset=20.
  4. If you find it, you've won! You don't need to simulate scrolling at all. Just write a loop in your spider to make requests to page=1, page=2, page=3, and so on, until the API stops returning new items. This is lightning-fast compared to browser automation.

Strategy 2: Automate the Scroll with Playwright (The Fallback)

If the infinite scroll is triggered by complex JavaScript events and not a clean API call, you'll need to simulate a user scrolling.

The idea is simple:

  1. Load the page with Playwright.
  2. Parse the initial items.
  3. Instruct the browser to scroll to the bottom of the page.
  4. Wait for a bit for new content to load.
  5. Check if new content has appeared. If so, parse it and repeat the scroll.
  6. If no new content appears after a scroll, you've reached the end.

Example using playwright_page_methods:

You can create a loop of requests, where each request scrolls down and waits.

python
# A simplified example of how you might approach this inside a spider
import scrapy
from scrapy_playwright.page import PageMethod

class InfiniteScrollSpider(scrapy.Spider):
    name = 'infinite_scroll'
    
    def start_requests(self):
        yield scrapy.Request(
            url="https://example.com/infinite-scroll-page",
            meta={
                "playwright": True,
                "playwright_page_methods": [
                    # Scroll to the bottom of the page
                    PageMethod("evaluate", "window.scrollTo(0, document.body.scrollHeight)"),
                    # Wait for 3 seconds to let new content load
                    PageMethod("wait_for_timeout", 3000),
                ],
            }
        )
    
    def parse(self, response):
        # Your parsing logic here to extract the items
        new_items = response.css('div.item::text').getall()

        # Here you would add logic to check if new items were loaded
        # and if so, yield another request to scroll again.
        # This can get complex and requires careful state management.
        
        yield {
            'items': new_items
        }

This approach is powerful but significantly slower and more fragile than hitting an API directly. A small change in the website's code can break your scroll-and-wait logic.


πŸ“š Further Reading & References

To continue your mastery, check out the official sources. They are the ultimate source of truth!

  • Scrapy Documentation: The official Scrapy docs are your primary guide for everything Scrapy-related.
  • scrapy-playwright GitHub Repository: The official page for the scrapy-playwright library, with detailed installation and usage examples.
  • Playwright Documentation: To understand all the powerful things you can make the browser do (like clicking buttons, filling forms, and taking screenshots), read the Playwright docs.
  • Browser Developer Tools: A great guide from Firefox on how to use the Network tab and other developer tools.

Challenge

You are tasked with scraping product data from an e-commerce site. After inspecting the browser's Network tab, you've discovered that the product information is not in the initial HTML but is loaded dynamically from a JSON API.

Your mission is to write a Scrapy spider that scrapes this data directly from the API endpoint, handling pagination correctly.

API Details:

  • Endpoint URL: https://api.example.com/products?page=1
  • Response Format: The API returns a JSON object with the following structure:
    json
    {
      "products": [
        {"name": "Product A", "price": "19.99", "sku": "A123"},
        {"name": "Product B", "price": "25.50", "sku": "B456"}
      ],
      "next_page_url": "https://api.example.com/products?page=2"
    }
  • Pagination: The JSON response contains a next_page_url key. If its value is a URL, your spider should follow it to get the next page of products. If the key's value is null or the key is absent, you have reached the last page.

Your Task:

Write a complete Scrapy spider that performs the following actions:

  1. Sets the spider's name to product_spider.
  2. Sets the start_urls to the initial API endpoint.
  3. Implements the parse method to:
    a. Decode the JSON response body.
    b. Iterate over the list of products.
    c. For each product, yield a dictionary containing only its name and price.
    d. Check for the next_page_url and, if it exists, yield a new scrapy.Request to follow the link, using the same parse method as the callback.

Expected result

Your final code should be a complete Scrapy spider class named ProductSpider.

  • The name attribute must be set to the string 'product_spider'.
  • The start_urls attribute must be a list containing the string 'https://api.example.com/products?page=1'.
  • The parse method must correctly process the response.
    • It must use json.loads(response.body) to parse the JSON data.
    • It should loop through each dictionary in the products list of the parsed data.
    • Inside the loop, it must yield a new dictionary for each product, structured as {'name': product['name'], 'price': product['price']}.
    • It must retrieve the next_page_url from the parsed data.
    • If a non-null next_page_url exists, it must yield a scrapy.Request(url=next_page_url, callback=self.parse) to handle pagination.
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.