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 →

Crawl in Python 2026: Building Modern Web Crawlers with Best Practices

Web Scraping Mar 24, 2026

Crawl in Python 2026: Building Modern Web Crawlers with Best Practices

Web crawling (also known as spidering) is the process of systematically browsing the internet to collect data. In 2026, building a responsible and efficient crawler involves asynchronous I/O, respectful rate limiting, proper user-agent identification, robots.txt compliance, and clean data pipelines.

This March 24, 2026 guide shows how to build a modern, classy Python crawler using current best practices with httpx, asyncio, BeautifulSoup, and ethical considerations.

TL;DR — Key Takeaways 2026

  • Use asynchronous requests with httpx for speed
  • Always respect robots.txt and add delays
  • Implement proper error handling and logging
  • Use BeautifulSoup or Playwright for parsing
  • Save data incrementally to avoid memory issues
  • Make your crawler identifiable and polite

1. Modern Classy Crawler Example


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

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

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

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

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

    async def crawl(self):
        queue = [self.start_url]
        while queue and len(self.visited) < self.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_links(html, url)
                queue.extend(new_links)
            except Exception as e:
                print(f"Failed to crawl {url}: {e}")

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

async def main():
    crawler = ClassyCrawler("https://www.example.com", delay=1.0, max_pages=30)
    await crawler.crawl()

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

2. Key Best Practices in 2026

  • Respect robots.txt — check before crawling
  • Polite delays — use asyncio.sleep between requests
  • Clear User-Agent — identify your crawler
  • Graceful error handling — never crash on single page failure
  • Incremental saving — write data as you crawl
  • Domain restriction — stay within allowed domains

3. When to Choose Different Tools

Tool Use Case Recommendation
httpx + BeautifulSoupStatic sitesFast and simple
Playwright / SeleniumJavaScript-heavy sitesWhen dynamic content is needed
ScrapyLarge-scale crawlingProduction-grade spiders
Asyncio + httpxHigh performanceModern custom crawlers

Crawling Within Clear Limits

A crawler follows links from page to page. Without limits it can wander across a whole site, revisit pages and send far more requests than intended. Good crawlers set a start URL, an allowed domain, a maximum number of pages and a delay between requests.

A queue of URLs to visit and a set of URLs already seen are the core of every crawler. Normalising URLs, for example by removing fragments, prevents the same page from being visited twice under slightly different addresses.

Scrapy provides these features through settings such as DOWNLOAD_DELAY, CLOSESPIDER_PAGECOUNT and allowed_domains, but the logic is easy to see in plain Python.

Worked Example: A Breadth-First Crawl on a Fake Site

We crawl a small site stored in a dictionary, so the logic can be tested without network access.

from collections import deque
from urllib.parse import urldefrag

SITE = {
    "/": ["/a", "/b#top", "https://other.example/"],
    "/a": ["/", "/c"],
    "/b": ["/c"],
    "/c": [],
}

def crawl(start="/", max_pages=10):
    queue, seen, order = deque([start]), {start}, []
    while queue and len(order) < max_pages:
        url = queue.popleft()
        order.append(url)
        for link in SITE.get(url, []):
            link = urldefrag(link).url
            if link.startswith("/") and link not in seen:
                seen.add(link)
                queue.append(link)
    return order

print(crawl())
print(crawl(max_pages=2))

The full crawl visits /, /a, /b and /c once each, skipping the external link and treating /b#top as /b. With max_pages=2 it stops after / and /a.

Practical Tips

Store the seen set in a file or database for long crawls, so an interrupted crawl can resume without visiting every page again.

Log every visited URL with its status code, which makes it easy to see where a crawl went wrong.

Common Mistakes

  • Not tracking seen URLs and looping forever.
  • Following links to other domains by accident.
  • Treating URLs with fragments as different pages.
  • Running without a page limit or delay.

Quick Summary

  • Use a queue and a seen set.
  • Normalise URLs before comparing.
  • Stay within the allowed domain.
  • Limit pages and add delays.

Conclusion — Building a Classy Crawler in 2026

A classy crawler is respectful, efficient, maintainable, and ethical. In 2026, the combination of asyncio, httpx, and BeautifulSoup provides an excellent foundation. Always prioritize politeness, error handling, and clean architecture. Whether for research, data collection, or learning, a well-built spider demonstrates both technical skill and responsibility.

Next steps:

  • Build your own crawler 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