Slashes and Brackets in Web Scraping with Python 2026: XPath vs CSS Explained Introduction to the Scrapy Selector in Python 2026 Setting up a Selector in Python 2026: Best Practices for Web Scraping Selecting Selectors in Python 2026: Best Practices for Web Scraping Extracting Data from a SelectorList in Python 2026: Best Practices CSS Locators in Python 2026: Powerful Web Scraping Techniques Attributes in CSS Selectors for Web Scraping in Python 2026 Selectors with CSS in Python 2026: Modern Web Scraping Techniques Text Extraction in Python 2026: Modern Techniques & Best Practices Crawl in Python 2026: Building Modern Web Crawlers with Best Practices A Classy Spider in Python 2026: Building Web Crawlers with Elegance & Best Practices Nodriver Canvas Fingerprint Spoofing 2026 – Advanced Anti-Detection Techniques WebGL Fingerprint Spoofing Techniques 2026 – Advanced Python Web Scrapping Evasion AudioContext Fingerprint Spoofing Techniques 2026 – Advanced Python Web Scrapping Evasion WebGL + AudioContext Integration Spoofing Techniques 2026 – Advanced Python Web Scrapping Evasion Canvas + WebGL Integration Spoofing Techniques 2026 – Advanced Python Web Scrapping Evasion Web Scraping with Python 2026 Web Scraping with Python in 2026 – Complete Beginner to Advanced Guide Python Web Scraping Tutorial 2026 – Playwright, Scrapy & BeautifulSoup Guide Building Your First Scrapy Spider in 2026 – Modern Python Web Scrapping Guide View all in this category →

A Classy Spider in Python 2026: Building Web Crawlers with Elegance & Best Practices

Web Scraping Mar 24, 2026

A Classy Spider in Python 2026: Building Web Crawlers with Elegance & Best Practices

Building a web crawler (often called a "spider") is a classic Python project that teaches asynchronous I/O, data extraction, rate limiting, and respectful crawling. In 2026, with improved async support, better libraries (httpx, BeautifulSoup4, Playwright, Scrapy), and stricter ethical guidelines, writing a "classy spider" means creating clean, efficient, respectful, and maintainable crawlers.

This March 24, 2026 update walks through building a modern, classy spider in Python using best practices: asynchronous requests, proper headers, rate limiting, data validation, error handling, and ethical considerations.

TL;DR — Key Takeaways 2026

  • Use httpx + asyncio for fast asynchronous crawling
  • Always respect robots.txt and add proper delays
  • Use BeautifulSoup or Playwright for parsing
  • Implement robust error handling and logging
  • Store data cleanly (JSON, CSV, or database)
  • Make your spider "classy" — modular, configurable, and respectful

1. Modern Classy Spider Structure


import asyncio
import httpx
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlparse
import time

class ClassySpider:
    def __init__(self, start_url: str, delay: float = 1.0):
        self.start_url = start_url
        self.delay = delay
        self.visited = set()
        self.client = httpx.AsyncClient(timeout=10.0, headers={
            "User-Agent": "ClassySpider/2026[](https://www.pyinns.com)"
        })

    async def fetch(self, url: str):
        await asyncio.sleep(self.delay)  # respectful delay
        response = await self.client.get(url)
        response.raise_for_status()
        return response.text

    async def parse(self, html: str, base_url: str):
        soup = BeautifulSoup(html, "html.parser")
        links = []
        for a in soup.find_all("a", href=True):
            link = urljoin(base_url, a["href"])
            if self.is_valid_url(link):
                links.append(link)
        return links

    def is_valid_url(self, url: str) -> bool:
        parsed = urlparse(url)
        return parsed.netloc == urlparse(self.start_url).netloc

    async def crawl(self, max_pages: int = 50):
        queue = [self.start_url]
        while queue and len(self.visited) < max_pages:
            url = queue.pop(0)
            if url in self.visited:
                continue
            self.visited.add(url)
            print(f"Crawling: {url}")
            try:
                html = await self.fetch(url)
                new_links = await self.parse(html, url)
                queue.extend(new_links)
            except Exception as e:
                print(f"Error crawling {url}: {e}")

        await self.client.aclose()
        print(f"Crawl finished. Visited {len(self.visited)} pages.")

# Usage
async def main():
    spider = ClassySpider("https://www.example.com")
    await spider.crawl(max_pages=30)

if __name__ == "__main__":
    asyncio.run(main())

2. Key Best Practices in 2026

  • Respect robots.txt — use urllib.robotparser or reppy
  • Add User-Agent — identify your crawler clearly
  • Rate limiting — use delays and async sleep
  • Error handling — graceful failures with logging
  • Data storage — save to JSON, CSV, or database incrementally
  • Ethical crawling — avoid aggressive scraping on production sites

3. When to Use Advanced Tools

Tool Use Case When to Choose
httpx + BeautifulSoupStatic pagesSimple, fast crawling
Playwright / SeleniumJavaScript-heavy sitesDynamic content
ScrapyLarge-scale crawlingProduction-grade spiders
Asyncio + httpxHigh performanceModern async spiders

What a Spider Class Organises

A Scrapy spider is a class that holds everything about one crawl: its name, where to start, which domains are allowed and how to parse each response. Keeping this together in a class makes the crawl easy to configure, test and reuse.

custom_settings lets each spider set its own politeness rules, such as DOWNLOAD_DELAY and ROBOTSTXT_OBEY, without changing the whole project. The parse method yields items as dictionaries and yields new requests to follow.

Because parse is an ordinary method, you can test it by building a response from saved HTML and checking the items it yields.

Worked Example: Testing a Spider's parse Method Offline

We define a small spider and feed its parse method a response built from saved HTML.

import scrapy
from scrapy.http import HtmlResponse

class QuoteSpider(scrapy.Spider):
    name = "quotes"
    allowed_domains = ["quotes.example"]
    custom_settings = {"DOWNLOAD_DELAY": 1, "ROBOTSTXT_OBEY": True}

    def parse(self, response):
        for q in response.css("div.quote"):
            yield {"text": q.css("span::text").get(), "author": q.css("small::text").get()}

html = b'<div class="quote"><span>Keep it simple.</span><small>Ana</small></div>'
response = HtmlResponse(url="https://quotes.example/", body=html, encoding="utf-8")
print(list(QuoteSpider().parse(response)))

The parse method yields one item with the text Keep it simple. and the author Ana. No request was sent, so the test runs quickly and does not depend on the site being online.

Practical Tips

Keep one spider per site or per data type, so settings and parsing rules stay focused and easy to review.

Common Mistakes

  • Putting politeness settings only in one developer's local settings file.
  • Leaving allowed_domains empty.
  • Testing spiders only against the live site.
  • Returning a list from parse instead of yielding items.

Quick Summary

  • A spider class groups all crawl logic.
  • custom_settings holds per-spider rules.
  • parse yields items and requests.
  • Test parse with HtmlResponse and saved HTML.

Conclusion — A Classy Spider in 2026

Building a classy spider means writing respectful, efficient, maintainable, and ethical crawlers. In 2026, combine asyncio with httpx, use proper delays, respect robots.txt, and implement clean architecture with classes. Whether for learning, data collection, or research, a well-written spider demonstrates both technical skill and responsibility.

Next steps:

  • Build your own classy spider starting with the example above

Related Tutorials

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices