spidermon
repository·master·Indexed 20 days ago
https://github.com/scrapinghub/spidermonA 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.
What's inside spidermon
- 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.
Overview of Spidermon features
masterSpidermon 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
jsonschemalibrary 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.
- Data Validation: Verifies output data (from Scrapy or other sources) against a schema or model. It supports validation using the
Configure Spidermon behavior via settings
masterSpidermon 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.How Monitors and MonitorSuites work
masterSpidermon uses two primary abstractions to validate spider execution:
- 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. - 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_MONITORSsetting insettings.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, ]- 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
How Monitor Suites work
masterA
MonitorSuitegroups multipleMonitorclasses 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.pyusing eitherSPIDERMON_SPIDER_OPEN_MONITORS(to run at spider start) orSPIDERMON_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 )What are Expression Monitors
masterExpression 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
TrueorFalse.When writing expressions, you have access to the following objects:
statscrawlerspiderjobvalidationresponses
How to use ValidationMonitorMixin in Monitors
masterThe
spidermon.contrib.monitors.mixins.ValidationMonitorMixinallows you to create monitors that check for validation errors in job stats.Method Groups
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.
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
_fieldtake a single field name. Methods ending in_fieldstake a list of field names. - Ratios vs Percentages: For
*_percentmethods, pass the ratio (e.g.,0.15for 15%), not the integer percentage. - Field List Handling: By default,
*_fieldsmethods combine error counts for all fields instead of checking them individually. To change this, set thecorrect_field_list_handlingmonitor attribute.
Use Spidermon Actions to automate post-monitor tasks
masterBy 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-actionslack-actiontelegram-actiondiscord-actionjob-tags-actionfile-report-actionsentry-actionsns-action
You can also implement
custom-actions to integrate with any other service.Use BaseStatMonitor to reduce boilerplate
masterWhen creating monitors that simply validate a numerical value from spider stats against a threshold, usespidermon.contrib.scrapy.monitors.base.BaseStatMonitor. This class provides a base to reduce boilerplate code for common threshold-based monitoring patterns.Configure the SNS action for AWS notifications
masterThe 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.pywith 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'Use the File Report Action to create reports from templates
masterThe
CreateFileReportaction allows you to generate a report file based on aJinja2template when a monitor suite finishes. To use it, addCreateFileReportto themonitors_finished_actionslist in yourMonitorSuiteclass 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"Configure a Telegram bot for Spidermon notifications
masterTo 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
- Create a Bot: Create a Telegram bot via the Telegram Bot API to receive your
Bot Authorization Token. - Identify Recipients: Obtain the
chat_idorgroup_idfor 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.
- Tip: You can use
- 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
/startcommand.
- Configure Scrapy Settings: Add the credentials to your
settings.pyfile.
# settings.py SPIDERMON_TELEGRAM_SENDER_TOKEN = "YOUR_BOT_AUTHORIZATION_TOKEN" SPIDERMON_TELEGRAM_RECIPIENTS = ["chat_id", "group_id", "@channelname"]- Create a Bot: Create a Telegram bot via the Telegram Bot API to receive your