spidermon

repository·master·Indexed 20 days ago

https://github.com/scrapinghub/spidermon

A framework and Scrapy extension for building monitors for Scrapy spiders. It provides tools for data validation, statistics monitoring, and automated notifications via actions such as Email (SES/SMTP), Slack, Discord, Sentry, and Amazon S3, allowing developers to monitor spider health through reports instead of manual log inspection.

Tokens
21.1K
Snippets
64
Records
86
Agent score
69%

What's inside spidermon

  1. Overview of Spidermon

    master
    Spidermon is a Scrapy extension designed for Python 3.10+. It provides a suite of tools to automate the monitoring of Scrapy spiders. Instead of manually checking spider logs, Spidermon allows you to delegate data validation, statistics monitoring, and notification management to the extension, which then provides reports and notifications based on your defined rules.
  2. Overview of Spidermon features

    master

    Spidermon is a framework designed to build monitors for Scrapy spiders. It provides several key capabilities for ensuring the quality and reliability of web scraping processes:

    • Data Validation: Verifies output data (from Scrapy or other sources) against a schema or model. It supports validation using the jsonschema library to enforce expected structures, data types, and value restrictions.
    • Stats Monitoring: Allows you to define specific conditions based on Scrapy stats that can trigger alerts.
    • Notifications: Supports sending alerts via multiple channels, including Email, Slack, Telegram, and Discord.
    • Reporting: Capable of generating custom reports based on spider execution.
  3. Configure Spidermon behavior via settings

    master
    Spidermon settings allow you to customize the behavior of your monitors. You can use these settings to enable or disable specific features, configure which monitors are active, define monitor actions, manage item validation, and set up notifications.
  4. How Monitors and MonitorSuites work

    master

    Spidermon uses two primary abstractions to validate spider execution:

    1. Monitors: Classes that contain monitoring logic. They are similar to test cases and use methods to validate data (e.g., checking item counts or data models). You can use @monitors.name("Name") to label your monitors and individual test methods.
    2. MonitorSuites: Collections of monitors. A suite defines which monitors to run and what actions (like notifications) to perform before or after the suite executes.

    To run a suite when a spider finishes, add the suite's import path to the SPIDERMON_SPIDER_CLOSE_MONITORS setting in settings.py.

    # tutorial/monitors.py
    from spidermon import Monitor, MonitorSuite, monitors
    
    @monitors.name("Item count")
    class ItemCountMonitor(Monitor):
        @monitors.name("Minimum number of items")
        def test_minimum_number_of_items(self):
            # Access spider stats via self.data.stats
            item_extracted = getattr(self.data.stats, "item_scraped_count", 0)
            minimum_threshold = 10
            msg = "Extracted less than {} items".format(minimum_threshold)
            self.assertTrue(item_extracted >= minimum_threshold, msg=msg)
    
    class SpiderCloseMonitorSuite(MonitorSuite):
        monitors = [
            ItemCountMonitor,
        ]
  5. How Monitor Suites work

    master

    A MonitorSuite groups multiple Monitor classes together and defines which actions should be executed based on the outcome of the monitoring process.

    To use a suite, you must register it in your Scrapy settings.py using either SPIDERMON_SPIDER_OPEN_MONITORS (to run at spider start) or SPIDERMON_SPIDER_CLOSE_MONITORS (to run at spider finish).

    # monitors.py
    from spidermon.core.suites import MonitorSuite
    
    class SpiderCloseMonitorSuite(MonitorSuite):
        monitors = [
            # list of Monitor classes
        ]
    
        monitors_finished_actions = [
            # actions to execute when suite finishes its execution
        ]
    
        monitors_failed_actions = [
            # actions to execute when suite finishes its execution with a failed monitor
        ]
    
    # settings.py
    SPIDERMON_SPIDER_OPEN_MONITORS = (
        # list of monitor suites to be executed when the spider starts
    )
    
    SPIDERMON_SPIDER_CLOSE_MONITORS = (
        # list of monitor suites to be executed when the spider finishes
    )
  6. What are Expression Monitors

    master

    Expression Monitors are monitors created on-the-fly when the Spidermon extension initializes. Instead of writing full Python classes, you can define tests using simple Python expressions within a dictionary in your settings. These expressions must evaluate to True or False.

    When writing expressions, you have access to the following objects:

    • stats
    • crawler
    • spider
    • job
    • validation
    • responses
  7. How to use ValidationMonitorMixin in Monitors

    master

    The spidermon.contrib.monitors.mixins.ValidationMonitorMixin allows you to create monitors that check for validation errors in job stats.

    Method Groups

    1. Missing Required Fields:

      • check_missing_required_fields / check_missing_required_field: Checks if the count of missing required fields is below a threshold.
      • check_missing_required_fields_percent / check_missing_required_field_percent: Checks if the ratio of missing required fields is below a threshold.
    2. General Field Errors:

      • check_fields_errors / check_field_errors: Checks if the count of errors in specified fields is below a threshold.
      • check_fields_errors_percent / check_field_errors_percent: Checks if the ratio of errors in specified fields is below a threshold.

    Important Notes

    • Naming Convention: Methods ending in _field take a single field name. Methods ending in _fields take a list of field names.
    • Ratios vs Percentages: For *_percent methods, pass the ratio (e.g., 0.15 for 15%), not the integer percentage.
    • Field List Handling: By default, *_fields methods combine error counts for all fields instead of checking them individually. To change this, set the correct_field_list_handling monitor attribute.
  8. Use Spidermon Actions to automate post-monitor tasks

    master

    By default, Spidermon includes pass/fail information in spider logs. However, for monitoring multiple spiders, you can define Actions that execute automatically after a monitor suite finishes. Actions allow you to push notifications or reports to external services instead of manually checking logs.

    Available built-in actions include:

    • email-action
    • slack-action
    • telegram-action
    • discord-action
    • job-tags-action
    • file-report-action
    • sentry-action
    • sns-action

    You can also implement custom-actions to integrate with any other service.

  9. Use BaseStatMonitor to reduce boilerplate

    master
    When creating monitors that simply validate a numerical value from spider stats against a threshold, use spidermon.contrib.scrapy.monitors.base.BaseStatMonitor. This class provides a base to reduce boilerplate code for common threshold-based monitoring patterns.
  10. Configure the SNS action for AWS notifications

    master

    The SNS action allows Spidermon to send custom notifications to an AWS Simple Notification Service (SNS) topic when monitor suites finish execution. To enable this, you must configure your settings.py with the required AWS credentials and the target SNS topic ARN.

    Security Warning: Do not commit your AWS access keys to public code repositories.

    # settings.py
    SPIDERMON_SNS_TOPIC_ARN = "<SNS_TOPIC_ARN>"
    SPIDERMON_AWS_ACCESS_KEY_ID = "<AWS_ACCESS_KEY>"
    SPIDERMON_AWS_SECRET_ACCESS_KEY = "<AWS_SECRET_KEY>"
    SPIDERMON_AWS_REGION_NAME = "<AWS_REGION_NAME>"  # Default is 'us-east-1'
  11. Use the File Report Action to create reports from templates

    master

    The CreateFileReport action allows you to generate a report file based on a Jinja2 template when a monitor suite finishes. To use it, add CreateFileReport to the monitors_finished_actions list in your MonitorSuite class and configure the report via settings.

    # monitors.py
    from spidermon.contrib.actions.reports.files import CreateFileReport
    
    
    class DummyMonitorSuite(MonitorSuite):
        monitors = [
            DummyMonitor,
        ]
    
        monitors_finished_actions = [
            CreateFileReport,
        ]
    
    # settings.py
    SPIDERMON_REPORT_TEMPLATE = "reports/email/monitors/result.jinja"
    SPIDERMON_REPORT_CONTEXT = {"report_title": "Spidermon File Report"}
    SPIDERMON_REPORT_FILENAME = "my_report.html"
  12. Configure a Telegram bot for Spidermon notifications

    master

    To send Spidermon notifications to Telegram using Telegram Actions, you must create a Telegram bot, obtain its authorization token, and configure your Scrapy project settings with the token and recipient IDs.

    Setup Steps

    1. Create a Bot: Create a Telegram bot via the Telegram Bot API to receive your Bot Authorization Token.
    2. Identify Recipients: Obtain the chat_id or group_id for the users, groups, or channels where you want notifications sent.
      • Tip: You can use [@GroupIDbot](https://t.me/GroupIDbot) to find these IDs by forwarding a message from the target user or group to the bot.
    3. Add Bot to Destination:
      • For Groups: Add your created bot as a member of the group.
      • For Channels: Add your created bot as an administrator of the channel.
      • For Private Users: The user must first start a conversation with the bot by sending the /start command.
    4. Configure Scrapy Settings: Add the credentials to your settings.py file.
    # settings.py
    SPIDERMON_TELEGRAM_SENDER_TOKEN = "YOUR_BOT_AUTHORIZATION_TOKEN"
    SPIDERMON_TELEGRAM_RECIPIENTS = ["chat_id", "group_id", "@channelname"]