Debugging, Logging, and Testing
7 min read
Debugging, Logging, and Testing in Scrapy 🕷️
Welcome, intrepid scraper! So, you've been slinging spiders and snatching data. But what happens when your spiders get tangled in the web, or you need to know what they're really up to in the dark corners of the internet? That's where debugging, logging, and testing come in. Think of these as your spider's toolkit: a magnifying glass, a detailed journal, and a rigorous training ground.
1. Configuring Scrapy Logging Levels 📜
The Problem: When you run your spider, a torrent of text floods your screen. Most of it seems like noise, and finding the important messages feels like searching for a needle in a haystack. How do you control this information overload and only see what you need?
The Solution: Logging Levels
Scrapy uses Python's built-in logging system, which categorizes messages by severity. Imagine you're a ship captain. You'd want to know about different issues with varying degrees of urgency.
Here are the standard logging levels in Scrapy, from most to least severe:
CRITICAL: System-shattering errors. "The ship is sinking!" Titanic-level problems.ERROR: Regular errors that prevent a specific task from completing. "The engine has stalled."WARNING: Something unexpected happened, but the spider can continue. "A large wave just splashed the deck."INFO: Informational messages about the spider's progress. "We've reached a new waypoint." By default, Scrapy shows messages of this level and higher.DEBUG: Detailed information, useful for tracking down bugs. "Checking the pressure in the third porthole." (Lowest severity).
How to Use Logging Levels
You can set the logging level in a couple of ways:
In your
settings.pyfile: This is the most common and recommended way to set a persistent logging level for your project.python# settings.py LOG_LEVEL = 'INFO'From the command line: This is great for a one-time change to see more or less detail.
bashscrapy crawl myspider -L WARNING # Or using the longer flag scrapy crawl myspider --loglevel WARNING
Logging from Your Spider
To log your own messages from within your spider, use self.logger.
import scrapy
class MySpider(scrapy.Spider):
name = 'myspider'
start_urls = ['http://quotes.toscrape.com']
def parse(self, response):
self.logger.info('Parse function called on %s', response.url)
for quote in response.css('div.quote'):
text = quote.css('span.text::text').get()
if not text:
self.logger.warning('Could not find quote text.')
yield {'text': text}🧐 Fun Fact: Excessive logging in a large-scale production environment can actually slow down your scraper and create massive log files. It's wise to log summaries instead of every single item scraped.
2. Using the parse Command and Shell for Debugging 🕵️♀️
The Problem: You've written your spider, but the selectors aren't quite right, and you're not getting the data you expect. Running the entire spider just to test a small change is slow and inefficient. You need a way to quickly test your code on a live response.
The Solution: Scrapy Shell and the parse Command
These tools are your secret weapons for rapid debugging.
Scrapy Shell: Your Interactive Playground
The Scrapy Shell is an interactive console that lets you test your selectors and code on a live URL without running your spider.
To launch it, simply run:
scrapy shell "http://quotes.toscrape.com"Once inside the shell, you have access to the response object. Now you can experiment with your CSS or XPath selectors in real-time.
# Inside the Scrapy Shell
>>> response.css('title::text').get()
'Quotes to Scrape'
>>> response.xpath('//div[@class="quote"]/span[@class="text"]/text()').getall()
['“The world as we have created it is a process of our thinking...', ... ]Pro-Tip: If you have IPython installed, the Scrapy shell will use it, giving you awesome features like auto-completion and colorized output.
The parse Command: A Spider's Rehearsal
The parse command lets you test a specific callback method of your spider on a given URL. This is incredibly useful for making sure your parsing logic is correct.
scrapy parse --spider=myspider -c parse "http://quotes.toscrape.com"This command will:
- Fetch the URL.
- Send the response to the
parsemethod ofmyspider. - Print the scraped items and any new requests that are generated.
The Ultimate Debugging Move: inspect_response
What if you want to pause your running spider and inspect a response right in the middle of its execution? inspect_response is your answer.
Simply add from scrapy.shell import inspect_response to your spider and then call inspect_response(response, self) where you want to pause.
import scrapy
from scrapy.shell import inspect_response
class MySpider(scrapy.Spider):
name = 'myspider'
start_urls = ['http://quotes.toscrape.com/page/1/']
def parse(self, response):
# Let's say we're having trouble with the second page
if "page/2" in response.url:
inspect_response(response, self)
for quote in response.css('div.quote'):
yield {'text': quote.css('span.text::text').get()}
next_page = response.css('li.next a::attr(href)').get()
if next_page is not None:
yield response.follow(next_page, self.parse)When the spider gets to the response you're interested in, it will open a Scrapy Shell, allowing you to inspect the response and other local variables. To continue the crawl, press Ctrl-D (or Ctrl-Z on Windows).
3. Handling Exceptions and Error Callbacks (errback) 🚑
The Problem: The internet is a messy place. Websites go down, servers return errors (like the infamous 404 or 500), and sometimes requests just fail. By default, Scrapy ignores these failed requests, but what if you need to log them, retry, or handle them in a specific way?
The Solution: The errback Parameter
When you create a scrapy.Request, you can provide an errback parameter. This is a callback function that will be executed if an exception occurs while processing the request.
import scrapy
from scrapy.spidermiddlewares.httperror import HttpError
from twisted.internet.error import DNSLookupError
from twisted.internet.error import TimeoutError, TCPTimedOutError
class MySpider(scrapy.Spider):
name = 'errback_example'
start_urls = [
"http://httpbin.org/status/404", # This will cause an HTTP error
"http://httpbin.org/delay/10", # This might time out
"http://www.a-domain-that-does-not-exist.com", # DNS error
]
def start_requests(self):
for url in self.start_urls:
yield scrapy.Request(url, callback=self.parse,
errback=self.errback_http_failure,
dont_filter=True)
def parse(self, response):
self.logger.info('Got successful response from %s', response.url)
def errback_http_failure(self, failure):
# log all failures
self.logger.error(repr(failure))
# in case you want to catch specific error types
if failure.check(HttpError):
# you can get the response
response = failure.value.response
self.logger.error('HttpError on %s', response.url)
elif failure.check(DNSLookupError):
# this is the original request
request = failure.request
self.logger.error('DNSLookupError on %s', request.url)
elif failure.check(TimeoutError, TCPTimedOutError):
request = failure.request
self.logger.error('TimeoutError on %s', request.url)In this example, if a request fails, the errback_http_failure method is called. It receives a Failure object, which contains information about the error. This gives you a robust way to handle different kinds of request failures gracefully.
4. Writing Unit Tests for Spiders and Contracts 🧪
The Problem: Your spider works perfectly today. But what happens next week when a teammate makes a change, or the website you're scraping alters its layout? Manually re-running and checking everything is tedious and error-prone.
The Solution: Spider Contracts
Scrapy has a built-in system for testing spiders called "contracts". Contracts allow you to write simple tests directly inside your spider's docstrings to verify its behavior.
A contract defines an example URL and the expected output for a callback.
import scrapy
class MyContractSpider(scrapy.Spider):
name = 'contract_spider'
def parse(self, response):
"""
@url http://quotes.toscrape.com
@returns items 10 10
@scrapes text author
"""
for quote in response.css('div.quote'):
yield {
'text': quote.css('span.text::text').get(),
'author': quote.css('small.author::text').get(),
}Let's break down the contract:
@url http://quotes.toscrape.com: Specifies the URL to use for the test.@returns items 10 10: Asserts that the callback should return between 10 and 10 items (inclusive).@scrapes text author: Checks that every returned item has both atextand anauthorfield.
To run your contracts, use the check command:
scrapy check contract_spiderScrapy will run the test and report if your spider's output matches the expectations defined in the contract. This is a fantastic way to ensure your spiders remain reliable over time.
Industry Practice: While Scrapy contracts are great for basic checks, for more complex logic (like in item pipelines or middlewares), developers often use standard Python testing frameworks like
unittestorpytest. Tools likescrapy-autounitcan even automatically generate basic unit tests for your spiders.
📚 Extra Reading
Challenge
You are tasked with creating a highly resilient and debuggable Scrapy spider named RobustProductSpider to scrape a website known for its instability.
Requirements:
- Spider Class: Define a class named
RobustProductSpiderthat inherits fromscrapy.Spider. - Initial Request: Implement the
start_requestsmethod. It must yield a singlescrapy.Requestfor the URL"http://unreliable-shop.com/products". This request must be configured to call a method namedhandle_failureif the request fails for any reason. - Parsing Logic & Debugging: Implement the
parsemethod.- It should first log an informational message:
"Successfully fetched product page". - If the
response.statusis not200, log aWARNINGmessage including the status code and then trigger the interactive debugging shell usinginspect_response. - If the
response.statusis200, it shouldyielda single dictionary:{"status": "parsed"}.
- It should first log an informational message:
- Error Handling: Implement the
handle_failuremethod. This method will receive the failure object from Scrapy.- It must first log a
CRITICALmessage using the request URL from the failure object. - Next, add specific checks for
HttpErrorandTimeoutError. If the failure is one of these types, log aWARNINGmessage identifying the specific error (e.g.,"HTTP Error encountered"or"Request timed out").
- It must first log a
- Contracts: Add a Scrapy contract to the
parsemethod's docstring to ensure its basic functionality. The contract must:- Use
"http://unreliable-shop.com/products"as the test URL. - Assert that the callback returns exactly 1 item.
- Assert that the scraped items contain a
statusfield.
- Use
Expected result
Your final code should be a complete Python class RobustProductSpider that correctly implements all the required functionality.
- The
start_requestsmethod should correctly yield ascrapy.Requestwith theurlanderrbackparameters properly set toself.handle_failure. - The
parsemethod's docstring must contain the three specified contract lines:@url,@returns items 1 1, and@scrapes status. - The body of the
parsemethod should useself.logger.info, contain anif/elseblock to checkresponse.status, callself.logger.warningandinspect_response(response, self)in the non-200 case, andyieldthe dictionary in the success case. - The
handle_failuremethod should acceptselfandfailureas arguments. It must useself.logger.criticalfor the general error message and includeif/elifstatements usingfailure.check(HttpError)andfailure.check(TimeoutError)to log specific warnings.