Learn Scrapy · 10/13

Performance Optimization & Settings

7 min read

Performance Optimization & Settings ⚙️

Welcome back, intrepid scraper! You've learned how to build spiders and extract data, but now it's time to tune up your engine. A powerful spider is great, but a fast and efficient spider is legendary. This guide will walk you through optimizing your Scrapy projects for better performance, responsible crawling, and a happier you.

Imagine your spider is a fleet of delivery drones. If they all swarm a single restaurant at once, they'll cause chaos and probably get shut down. But if you coordinate them, space out their pickups, and give them a local warehouse to store common items, your delivery empire will run like a well-oiled machine. That's what we're doing today with your spiders.


1. Tuning Concurrency and Download Delays 🏎️

The Problem: By default, Scrapy is like an over-caffeinated intern—it tries to do everything at once, as fast as possible. This can overwhelm the websites you're scraping, leading to your spider getting blocked or even causing issues for the site. Plus, sending requests too quickly can sometimes be less efficient.

The Solution: We can control the speed and number of simultaneous requests Scrapy makes. This is not only polite to the server but also makes your spider more resilient.

CONCURRENT_REQUESTS

This setting controls the maximum number of requests that Scrapy's downloader will perform at the same time. The default is 16.

  • When to change it: If you're scraping a single, robust website (like a major e-commerce site), you might be able to increase this. If you're scraping multiple smaller sites or a site that is sensitive to traffic, you might want to decrease it. A good starting point for broad crawls across many domains is 100.

Example in settings.py:

python
# settings.py
CONCURRENT_REQUESTS = 32 # Doubling the default

DOWNLOAD_DELAY

This is the number of seconds to wait between consecutive requests to the same website. The default is 0.

  • Fun Fact: To avoid being too predictable, Scrapy, by default, uses a random interval between 0.5 and 1.5 times your DOWNLOAD_DELAY. So, a DOWNLOAD_DELAY of 2 will result in waits between 1 and 3 seconds. This helps mimic more human-like browsing behavior.

Example in settings.py:

python
# settings.py
DOWNLOAD_DELAY = 2  # Wait 2 seconds between requests to the same domain

AutoThrottle Extension: The Smart Approach

Manually setting delays can be a bit of a guessing game. This is where the AutoThrottle extension comes in. It's a built-in Scrapy feature that automatically adjusts the delay between requests based on the server's response time and load. This is fantastic because it's adaptive; if the server is busy, your spider backs off. If it's quick, your spider speeds up.

To enable AutoThrottle, add this to your settings.py:

python
# settings.py
AUTOTHROTTLE_ENABLED = True
AUTOTHROTTLE_START_DELAY = 5  # The initial download delay (default: 5.0)
AUTOTHROTTLE_MAX_DELAY = 60  # The maximum download delay to be set in case of high latencies (default: 60.0)
AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 # The average number of requests Scrapy should be sending in parallel to every remote server
AUTOTHROTTLE_DEBUG = False  # Set to True to see the throttling stats for every response.

By enabling AUTOTHROTTLE, Scrapy will try to be a "good citizen" of the web.


2. Enabling and Configuring the HTTP Cache 💾

The Problem: When you're developing and debugging a spider, you often run it many times. Each time, it re-downloads the same pages. This is slow, uses unnecessary bandwidth, and can get you temporarily blocked for making too many requests.

The Solution: Scrapy has a built-in HTTP caching middleware that saves a local copy of every page your spider visits. On subsequent runs, if the page is requested again, Scrapy uses the saved copy instead of re-downloading it. This is a massive time-saver during development.

How to Enable It:
It's as simple as adding one line to your settings.py:

python
# settings.py
HTTPCACHE_ENABLED = True

With this enabled, a .scrapy/httpcache directory will be created in your project folder to store the cached responses.

Useful HTTP Cache Settings:

  • HTTPCACHE_EXPIRATION_SECS: How long to keep the cache, in seconds. If set to 0 (the default), the cache never expires.
  • HTTPCACHE_DIR: The directory to store the cache. The default is httpcache.
  • HTTPCACHE_IGNORE_HTTP_CODES: A list of HTTP status codes to not cache.
  • HTTPCACHE_POLICY: The caching policy to use. The default is scrapy.extensions.httpcache.DummyPolicy. For web-aware caching that respects Cache-Control headers, use scrapy.extensions.httpcache.RFC2616Policy.

A Practical Development Setup:

python
# settings.py
HTTPCACHE_ENABLED = True
HTTPCACHE_EXPIRATION_SECS = 0  # Never expire for development
HTTPCACHE_DIR = 'httpcache'

Pro-Tip: When you're ready to deploy your spider to production for a "real" run, you'll likely want to disable the cache or set a reasonable expiration time to ensure you're getting fresh data. You can disable it at runtime with a command-line flag.

bash
scrapy crawl myspider -s HTTPCACHE_ENABLED=False

3. Optimizing Memory Usage and Preventing Leaks 💧

The Problem: As your spider crawls more and more pages, its memory usage can grow. In some cases, due to how your code is written, Scrapy might hold on to objects in memory that it no longer needs. This is called a "memory leak." A leaky spider will slow down and eventually crash, especially on large crawls.

The Solution: Writing memory-efficient spiders and knowing how to debug memory issues are crucial skills.

Common Causes of Memory Leaks:
The most frequent cause of memory leaks in Scrapy is when you pass references to objects (like responses or items) in the meta attribute of a Request. This can create a long chain of objects that can't be cleared from memory.

Debugging Memory Leaks:
Scrapy has a built-in tool called trackref to help you find leaks. You can access it through the Telnet console. It tracks live Scrapy objects like Requests, Responses, and Items.

You can also use a third-party library like muppy for more in-depth memory analysis.

Best Practices for Memory Management:

  • Process Items Immediately: Don't accumulate items in a list within your spider. Yield them to your item pipeline as soon as they are scraped.
  • Limit Request Depth: For sites with deep or infinite pagination, set a depth limit to prevent your spider from crawling forever.
    python
    # settings.py
    DEPTH_LIMIT = 3
  • Enable Memory Usage Limits: Scrapy can monitor its own memory usage and notify you or even shut down if it exceeds a certain limit.
    python
    # settings.py
    MEMUSAGE_ENABLED = True
    MEMUSAGE_LIMIT_MB = 2048  # 2GB limit
    MEMUSAGE_WARNING_MB = 1536 # Warning at 1.5GB

It's also worth noting that sometimes Python itself may not return released memory back to the operating system, which can give the appearance of a leak even when your code is correct.


4. Managing Built-in Scrapy Settings (settings.py) 🛠️

The Problem: Scrapy has a lot of settings. It can be overwhelming to know which ones are important and how to use them effectively.

The Solution: Think of settings.py as your spider's control panel. While there are many options, you'll find yourself using a core set of them regularly.

Three Levels of Settings:
Scrapy's settings have a hierarchy of precedence:

  1. Command-line options (-s or --set): Highest precedence.
  2. Settings per-spider (custom_settings): Overrides project settings for a specific spider.
  3. Project settings module (settings.py): The main configuration for your project.
  4. Default global settings: The baseline settings built into Scrapy.

Example of custom_settings in a Spider:
This is super useful when you have one spider that needs to behave differently from the others in the same project.

python
import scrapy

class FastSpider(scrapy.Spider):
    name = 'fast_spider'
    start_urls = ['http://example.com']

    custom_settings = {
        'DOWNLOAD_DELAY': 0.5,
        'CONCURRENT_REQUESTS_PER_DOMAIN': 16,
    }

    def parse(self, response):
        # ... your parsing logic ...
        pass

Key Settings You Should Know:

  • BOT_NAME: The name of your bot. It's good practice to set this to something descriptive.
  • USER_AGENT: The User-Agent string sent with your requests. The default is something like "Scrapy/2.11.0 (+https://scrapy.org)". It's often a good idea to change this to mimic a real browser to avoid being blocked.
  • ROBOTSTXT_OBEY: By default, this is True, meaning Scrapy will respect the robots.txt file of websites. Changing this to False is possible, but be sure you have permission and are not violating the website's terms of service.
  • LOG_LEVEL: Controls the verbosity of your logs. During development, INFO or DEBUG is useful. In production, you might set it to WARNING or ERROR to reduce noise.

By mastering these performance and settings concepts, you'll be well on your way to building robust, efficient, and well-behaved web scrapers. Happy scraping! 🚀


Extra Reading & References 📚

Challenge

You are tasked with configuring a Scrapy project that contains two spiders with very different crawling strategies. Your goal is to set up both global project settings and spider-specific overrides to ensure optimal performance and responsible crawling behavior.

In the editor below, you will find skeletons for two conceptual files: settings.py and spiders/my_spiders.py. Fill them out according to the requirements below.

Global Configuration (settings.py)

  1. Set the USER_AGENT to mimic a recent version of Chrome on a desktop (e.g., Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36).
  2. Enable the HTTP cache (HTTPCACHE_ENABLED) for development purposes.
  3. Configure the HTTP cache to never expire (HTTPCACHE_EXPIRATION_SECS).
  4. Enable the memory usage extension (MEMUSAGE_ENABLED).
  5. Set the memory usage limit (MEMUSAGE_LIMIT_MB) to 2048 MB.
  6. Set the memory usage warning threshold (MEMUSAGE_WARNING_MB) to 1536 MB.
  7. Ensure the project respects robots.txt rules (ROBOTS_TXT_OBEY).
  8. Set the default logging level (LOG_LEVEL) to INFO.

Spider-Specific Configuration (spiders/my_spiders.py)

BroadSpider (for a large, robust website):

  1. Within the BroadSpider class, use custom_settings to override the default concurrency. Set CONCURRENT_REQUESTS to 64.
  2. Enable the AutoThrottle extension (AUTOTHROTTLE_ENABLED) specifically for this spider.
  3. Set the AUTOTHROTTLE_TARGET_CONCURRENCY to 32.0.

GentleSpider (for a small, sensitive archive):

  1. Within the GentleSpider class, use custom_settings to implement a polite crawling policy.
  2. Set a fixed DOWNLOAD_DELAY of 3 seconds.
  3. Limit the maximum crawl depth (DEPTH_LIMIT) to 5.
  4. Explicitly disable the AutoThrottle extension for this spider to ensure the fixed delay is always respected.

Expected result

Your final code should consist of two sections, settings.py and spiders/my_spiders.py, with the correct Scrapy settings implemented.

In the settings.py section:

  • USER_AGENT should be a string resembling a modern browser, for example: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'.
  • HTTPCACHE_ENABLED must be set to True.
  • HTTPCACHE_EXPIRATION_SECS must be set to 0.
  • MEMUSAGE_ENABLED must be set to True.
  • MEMUSAGE_LIMIT_MB must be set to 2048.
  • MEMUSAGE_WARNING_MB must be set to 1536.
  • ROBOTS_TXT_OBEY must be set to True.
  • LOG_LEVEL must be set to 'INFO'.

In the spiders/my_spiders.py section:

  • The BroadSpider class must have a custom_settings dictionary containing:
    • 'CONCURRENT_REQUESTS': 64
    • 'AUTOTHROTTLE_ENABLED': True
    • 'AUTOTHROTTLE_TARGET_CONCURRENCY': 32.0
  • The GentleSpider class must have a custom_settings dictionary containing:
    • 'DOWNLOAD_DELAY': 3
    • 'DEPTH_LIMIT': 5
    • 'AUTOTHROTTLE_ENABLED': False
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.