This is a comprehensive request for building a web crawler with several important features:
- Politeness policy - respecting robots.txt
- Parse robots.txt using urllib.robotparser
- Token bucket rate limiter - max 1 request per second per domain
- Concurrent crawling with asyncio
- Handle multiple domains
I'll create a complete solution with:
- RobotParser wrapper to handle robots.txt
- Token bucket rate limiter
- Async crawler with proper concurrency control
- Proper error handling
- Example usage
Let me structure this well:
- Token Bucket Rate Limiter
- RobotsParser wrapper
- Async HTTP client wrapper
- Main Crawler class
- Example usage with multiple domains
Important considerations:
- Thread-safe token bucket for async operations
- Respect User-Agent in robots.txt
- Cache parsed robots.txt
- Proper error handling for network failures
- Request headers (User-Agent)
- Domain-specific rate limiting
- Crawl delay from robots.txt
- Concurrent operations with asyncio
- URL validation
- Logging
Let me write comprehensive code:
Web Crawler with Politeness Policy and Rate Limiting
I'll build a complete web crawler with robots.txt parsing, token bucket rate limiting, and concurrent crawling capabilities.
import asyncio
import time
import logging
from typing import Dict, List, Optional, Set, Tuple
from urllib.robotparser import RobotFileParser
from urllib.parse import urljoin, urlparse
from datetime import datetime, timedelta
import aiohttp
from dataclasses import dataclass, field
from collections import defaultdict
import hashlib
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
@dataclass
class CrawlResult:
"""Result of a single crawl operation"""
url: str
status_code: Optional[int] = None
content: Optional[str] = None
links: List[str] = field(default_factory=list)
error: Optional[str] = None
timestamp: datetime = field(default_factory=datetime.now)
def is_success(self) -> bool:
return self.status_code == 200 and self.error is None
class TokenBucket:
"""
Token bucket rate limiter for async operations.
Ensures smooth rate limiting across async operations.
"""
def __init__(self, capacity: float, refill_rate: float):
"""
Args:
capacity: Maximum tokens in bucket
refill_rate: Tokens per second
"""
self.capacity = capacity
self.refill_rate = refill_rate
self.tokens = capacity
self.last_update = time.monotonic()
self._lock = asyncio.Lock()
async def acquire(self, tokens: float = 1.0) -> None:
"""
Acquire tokens from bucket. Waits if not enough tokens available.
Args:
tokens: Number of tokens to acquire
"""
async with self._lock:
while not await self._try_acquire(tokens):
# Calculate wait time
now = time.monotonic()
refill_time = (tokens - self.tokens) / self.refill_rate
await asyncio.sleep(refill_time)
self._refill()
async def _try_acquire(self, tokens: float) -> bool:
"""Try to acquire tokens without waiting"""
self._refill()
if self.tokens >= tokens:
self.tokens -= tokens
return True
return False
def _refill(self) -> None:
"""Refill bucket based on elapsed time"""
now = time.monotonic()
elapsed = now - self.last_update
self.tokens = min(
self.capacity,
self.tokens + elapsed * self.refill_rate
)
self.last_update = now
class RobotsParser:
"""
Wrapper around urllib.robotparser.RobotFileParser
Handles caching and concurrent access to robots.txt files
"""
def __init__(self, user_agent: str = "PoliteBot/1.0", cache_ttl: int = 3600):
"""
Args:
user_agent: User agent string for robots.txt requests
cache_ttl: Cache time-to-live in seconds
"""
self.user_agent = user_agent
self.cache_ttl = cache_ttl
self.parsers: Dict[str, Tuple[RobotFileParser, float]] = {}
self._lock = asyncio.Lock()
async def get_robots_parser(self, domain: str) -> RobotFileParser:
"""
Get RobotFileParser for a domain, with caching
Args:
domain: Domain name (e.g., 'example.com')
Returns:
RobotFileParser instance
"""
async with self._lock:
now = time.time()
# Return cached parser if valid
if domain in self.parsers:
parser, timestamp = self.parsers[domain]
if now - timestamp < self.cache_ttl:
logger.debug(f"Using cached robots.txt for {domain}")
return parser
# Create and cache new parser
parser = RobotFileParser()
parser.set_url(f"https://{domain}/robots.txt")
try:
parser.read()
logger.info(f"Successfully parsed robots.txt for {domain}")
except Exception as e:
logger.warning(f"Failed to fetch robots.txt for {domain}: {e}")
# Create empty parser (allow all)
parser = RobotFileParser()
self.parsers[domain] = (parser, now)
return parser
async def can_fetch(self, url: str) -> bool:
"""
Check if URL can be fetched according to robots.txt
Args:
url: Full URL to check
Returns:
True if URL can be fetched, False otherwise
"""
parsed = urlparse(url)
domain = parsed.netloc
parser = await self.get_robots_parser(domain)
can_fetch = parser.can_fetch(self.user_agent, url)
if not can_fetch:
logger.warning(f"robots.txt disallows fetching: {url}")
return can_fetch
async def get_crawl_delay(self, domain: str) -> float:
"""
Get crawl delay for domain from robots.txt
Args:
domain: Domain name
Returns:
Crawl delay in seconds (default 1.0)
"""
parser = await self.get_robots_parser(domain)
delay = parser.request_rate(self.user_agent)
if delay:
return delay.seconds
# Try request-rate as fallback
try:
crawl_delay = parser.crawl_delay(self.user_agent)
if crawl_delay:
return crawl_delay
except AttributeError:
pass
# Default to 1 second
return 1.0
class RateLimiter:
"""
Per-domain rate limiter using token buckets
"""
def __init__(self, default_rate: float = 1.0):
"""
Args:
default_rate: Default requests per second per domain
"""
self.default_rate = default_rate
self.buckets: Dict[str, TokenBucket] = defaultdict(
lambda: TokenBucket(capacity=1.0, refill_rate=self.default_rate)
)
self._lock = asyncio.Lock()
async def acquire(self, domain: str, tokens: float = 1.0) -> None:
"""
Acquire permission to make a request to a domain
Args:
domain: Domain name
tokens: Number of tokens to acquire
"""
bucket = self.buckets[domain]
logger.debug(f"Acquiring {tokens} tokens for {domain}")
await bucket.acquire(tokens)
async def set_rate(self, domain: str, rate: float) -> None:
"""
Set custom rate for a domain (e.g., from robots.txt)
Args:
domain: Domain name
rate: Requests per second
"""
async with self._lock:
self.buckets[domain] = TokenBucket(
capacity=1.0,
refill_rate=rate
)
logger.info(f"Set rate for {domain} to {rate} req/s")
class WebCrawler:
"""
Async web crawler with politeness policy and rate limiting
"""
def __init__(
self,
user_agent: str = "PoliteBot/1.0",
timeout: int = 10,
max_pages_per_domain: int = -1,
robots_cache_ttl: int = 3600
):
"""
Args:
user_agent: User agent string
timeout: Request timeout in seconds
max_pages_per_domain: Max pages to crawl per domain (-1 for unlimited)
robots_cache_ttl: robots.txt cache TTL in seconds
"""
self.user_agent = user_agent
self.timeout = timeout
self.max_pages_per_domain = max_pages_per_domain
self.robots_parser = RobotsParser(user_agent, robots_cache_ttl)
self.rate_limiter = RateLimiter()
self.visited: Set[str] = set()
self.pages_per_domain: Dict[str, int] = defaultdict(int)
self._lock = asyncio.Lock()
def _get_domain(self, url: str) -> str:
"""Extract domain from URL"""
return urlparse(url).netloc
async def _get_session(self) -> aiohttp.ClientSession:
"""Get or create aiohttp session"""
return aiohttp.ClientSession(
headers={"User-Agent": self.user_agent},
timeout=aiohttp.ClientTimeout(total=self.timeout)
)
async def _extract_links(self, content: str, base_url: str) -> List[str]:
"""
Extract links from HTML content
Args:
content: HTML content
base_url: Base URL for resolving relative links
Returns:
List of absolute URLs
"""
import re
links = []
# Simple regex for href extraction (in production, use BeautifulSoup)
href_pattern = r'href=["\']([^"\']+)["\']'
for href in re.findall(href_pattern, content):
try:
# Resolve relative URLs
absolute_url = urljoin(base_url, href)
# Only include http/https URLs
if absolute_url.startswith(('http://', 'https://')):
links.append(absolute_url)
except Exception as e:
logger.debug(f"Failed to process link {href}: {e}")
return links
async def _should_crawl(self, url: str) -> Tuple[bool, Optional[str]]:
"""
Check if URL should be crawled
Args:
url: URL to check
Returns:
Tuple of (should_crawl, reason_if_not)
"""
# Check if already visited
if url in self.visited:
return False, "Already visited"
# Check robots.txt
domain = self._get_domain(url)
if not await self.robots_parser.can_fetch(url):
return False, "Disallowed by robots.txt"
# Check domain page limit
async with self._lock:
if self.max_pages_per_domain > 0:
if self.pages_per_domain[domain] >= self.max_pages_per_domain:
return False, f"Exceeded max pages for domain ({self.max_pages_per_domain})"
return True, None
async def crawl_url(
self,
url: str,
session: Optional[aiohttp.ClientSession] = None
) -> CrawlResult:
"""
Crawl a single URL with rate limiting and politeness policy
Args:
url: URL to crawl
session: aiohttp session (created if None)
Returns:
CrawlResult object
"""
# Check if should crawl
should_crawl, reason = await self._should_crawl(url)
if not should_crawl:
logger.info(f"Skipping {url}: {reason}")
return CrawlResult(url=url, error=f"Skipped: {reason}")
domain = self._get_domain(url)
# Rate limiting
try:
await self.rate_limiter.acquire(domain)
except Exception as e:
logger.error(f"Rate limiting error for {url}: {e}")
return CrawlResult(url=url, error=f"Rate limiting error: {e}")
# Mark as visited
async with self._lock:
self.visited.add(url)
self.pages_per_domain[domain] += 1
# Fetch URL
session_created = False
try:
if session is None:
session = await self._get_session()
session_created = True
logger.info(f"Crawling: {url}")
start_time = time.time()
async with session.get(url, ssl=False) as response:
elapsed = time.time() - start_time
logger.info(
f"Status {response.status} for {url} ({elapsed:.2f}s)"
)
if response.status == 200:
content = await response.text(errors='ignore')
links = await self._extract_links(content, url)
return CrawlResult(
url=url,
status_code=response.status,
content=content[:1000], # Store first 1000 chars
links=links
)
else:
return CrawlResult(
url=url,
status_code=response.status,
error=f"HTTP {response.status}"
)
except asyncio.TimeoutError:
error_msg = f"Timeout after {self.timeout}s"
logger.error(f"{url}: {error_msg}")
return CrawlResult(url=url, error=error_msg)
except aiohttp.ClientError as e:
error_msg = f"Client error: {str(e)}"
logger.error(f"{url}: {error_msg}")
return CrawlResult(url=url, error=error_msg)
except Exception as e:
error_msg = f"Unexpected error: {str(e)}"
logger.error(f"{url}: {error_msg}")
return CrawlResult(url=url, error=error_msg)
finally:
if session_created:
await session.close()
async def crawl_urls(
self,
urls: List[str],
max_concurrent: int = 5
) -> List[CrawlResult]:
"""
Crawl multiple URLs concurrently with rate limiting per domain
Args:
urls: List of URLs to crawl
max_concurrent: Maximum concurrent requests
Returns:
List of CrawlResult objects
"""
results = []
semaphore = asyncio.Semaphore(max_concurrent)
async def crawl_with_semaphore(url: str, session: aiohttp.ClientSession):
async with semaphore:
return await self.crawl_url(url, session)
# Use single session for all requests
session = await self._get_session()
try:
tasks = [
crawl_with_semaphore(url, session)
for url in urls
]
results = await asyncio.gather(*tasks)
finally:
await session.close()
return results
async def crawl_domain(
self,
start_url: str,
max_pages: int = 10,
max_depth: int = 2
) -> List[CrawlResult]:
"""
Crawl a domain starting from a URL with BFS
Args:
start_url: URL to start crawling from
max_pages: Maximum pages to crawl
max_depth: Maximum depth for crawling
Returns:
List of CrawlResult objects
"""
results = []
queue = [(start_url, 0)] # (url, depth)
visited = set()
domain = self._get_domain(start_url)
semaphore = asyncio.Semaphore(3) # 3 concurrent per domain
async def crawl_with_semaphore(url: str, session: aiohttp.ClientSession):
async with semaphore:
return await self.crawl_url(url, session)
session = await self._get_session()
try:
while queue and len(results) < max_pages:
url, depth = queue.pop(0)
if url in visited or depth > max_depth:
continue
visited.add(url)
# Only crawl URLs from same domain
if self._get_domain(url) != domain:
continue
result = await crawl_with_semaphore(url, session)
results.append(result)
# Add discovered links to queue
if result.is_success():
for link in result.links[:5]: # Limit links per page
if link not in visited:
queue.append((link, depth + 1))
finally:
await session.close()
return results
async def crawl_with_robots_delay(
self,
urls: List[str],
apply_crawl_delay: bool = True
) -> List[CrawlResult]:
"""
Crawl URLs with crawl delay from robots.txt
Args:
urls: List of URLs to crawl
apply_crawl_delay: Whether to apply robots.txt crawl_delay
Returns:
List of CrawlResult objects
"""
if apply_crawl_delay:
# Apply crawl delays from robots.txt
domains = set(self._get_domain(url) for url in urls)
for domain in domains:
delay = await self.robots_parser.get_crawl_delay(domain)
await self.rate_limiter.set_rate(domain, 1.0 / delay)
return await self.crawl_urls(urls)
def get_stats(self) -> Dict:
"""Get crawling statistics"""
return {
"total_visited": len(self.visited),
"pages_per_domain": dict(self.pages_per_domain),
"rate_limiters": list(self.rate_limiter.buckets.keys())
}
# ============================================================================
# Example Usage
# ============================================================================
async def main():
"""Main example demonstrating crawler usage"""
# Initialize crawler
crawler = WebCrawler(
user_agent="PoliteBot/1.0 (+http://example.com/bot)",
timeout=10,
max_pages_per_domain=5
)
# Example 1: Crawl multiple URLs concurrently
print("\n" + "="*60)
print("Example 1: Crawling Multiple URLs Concurrently")
print("="*60)
urls = [
"https://httpbin.org/html",
"https://httpbin.org/delay/1",
"https://example.com",
"https://example.org",
]
results = await crawler.crawl_urls(urls, max_concurrent=2)
print(f"\nCrawl Results:")
for result in results:
status = "✓" if result.is_success() else "✗"
print(f"{status} {result.url}")
if result.error:
print(f" Error: {result.error}")
else:
print(f" Status: {result.status_code}")
if result.links:
print(f" Found {len(result.links)} links")
# Example 2: Crawl single domain with depth
print("\n" + "="*60)
print("Example 2: Crawling Single Domain with BFS")
print("="*60)
domain_results = await crawler.crawl_domain(
start_url="https://example.com",
max_pages=5,
max_depth=1
)
print(f"\nDomain Crawl Results:")
for result in domain_results:
status = "✓" if result.is_success() else "✗"
print(f"{status} {result.url}")
# Example 3: Test rate limiting
print("\n" + "="*60)
print("Example 3: Testing Rate Limiting")
print("="*60)
test_urls = [
"https://httpbin.org/delay/1",
"https://httpbin.org/status/200",
"https://httpbin.org/html",
]
start_time = time.time()
rate_results = await crawler.crawl_urls(test_urls, max_concurrent=1)
elapsed = time.time() - start_time
print(f"\nRate Limiting Results:")
print(f"Crawled {len(rate_results)} URLs in {elapsed:.2f} seconds")
print(f"Average rate: {len(rate_results)/elapsed:.2f} req/s")
# Example 4: Statistics
print("\n" + "="*60)
print("Crawler Statistics")
print("="*60)
stats = crawler.get_stats()
print(f"\nTotal visited: {stats['total_visited']}")
print(f"Pages per domain: {stats['pages_per_domain']}")
async def stress_test():
"""Stress test with many concurrent domains"""
print("\n" + "="*60)
print("Stress Test: Multiple Domains Concurrent Crawling")
print("="*60)
crawler = WebCrawler(
user_agent="PoliteBot/1.0",
timeout=10,
max_pages_per_domain=-1
)
# URLs from different domains
urls = [
"https://httpbin.org/get",
"https://httpbin.org/post",
"https://example.com",
"https://example.org",
"https://example.net",
]
start_time = time.time()
results = await crawler.crawl_urls(urls * 2, max_concurrent=5)
elapsed = time.time() - start_time
successful = sum(1 for r in results if r.is_success())
print(f"\nStress Test Results:")
print(f"Total requests: {len(results)}")
print(f"Successful: {successful}")
print(f"Failed: {len(results) - successful}")
print(f"Time taken: {elapsed:.2f}s")
print(f"Requests per second: {len(results)/elapsed:.2f}")
for domain, count in crawler.get_stats()['pages_per_domain'].items():
print(f" {domain}: {count} pages")
async def demonstrate_rate_limiting():
"""Demonstrate per-domain rate limiting"""
print("\n" + "="*60)
print("Rate Limiting Demonstration")
print("="*60)
crawler = WebCrawler(user_agent="PoliteBot/1.0")
# Create URLs for same domain
same_domain_urls = [
"https://httpbin.org/delay/1",
"https://httpbin.org/delay/1",
"https://httpbin.org/delay/1",
"https://httpbin.org/delay/1",
]
print("\nCrawling 4 URLs from same domain (rate limit: 1 req/s):")
print("Expected duration: ~4 seconds\n")
start_time = time.time()
results = await crawler.crawl_urls(same_domain_urls, max_concurrent=10)
elapsed = time.time() - start_time
print(f"Actual duration: {elapsed:.2f} seconds")
print(f"Rate: {len(results)/elapsed:.2f} req/s")
if __name__ == "__main__":
# Run examples
asyncio.run(main())
asyncio.run(stress_test())
asyncio.run(demonstrate_rate_limiting())
Advanced Features Example
class AdvancedWebCrawler(WebCrawler):
"""Extended crawler with additional features"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.request_cache: Dict[str, Tuple[CrawlResult, float]] = {}
self.cache_ttl = 300 # 5 minutes
async def crawl_url_cached(
self,
url: str,
session: Optional[aiohttp.ClientSession] = None,
use_cache: bool = True
) -> CrawlResult:
"""
Crawl URL with caching
Args:
url: URL to crawl
session: aiohttp session
use_cache: Whether to use cache
Returns:
CrawlResult object
"""
now = time.time()
# Check cache
if use_cache and url in self.request_cache:
result, timestamp = self.request_cache[url]
if now - timestamp < self.cache_ttl:
logger.info(f"Cache hit for {url}")
return result
# Crawl
result = await self.crawl_url(url, session)
# Cache result
if result.is_success():
self.request_cache[url] = (result, now)
return result
async def crawl_sitemap(self, sitemap_url: str) -> List[CrawlResult]:
"""
Crawl URLs from XML sitemap
Args:
sitemap_url: URL of sitemap.xml
Returns:
List of CrawlResult objects
"""
import xml.etree.ElementTree as ET
results = []
try:
session = await self._get_session()
# Fetch sitemap
async with session.get(sitemap_url, ssl=False) as response:
if response.status != 200:
logger.error(f"Failed to fetch sitemap: {response.status}")
return results
content = await response.text()
# Parse sitemap
root = ET.fromstring(content)
namespace = {'ns': 'http://www.sitemaps.org/schemas/sitemap/0.9'}
urls = [
loc.text
for loc in root.findall('.//ns:loc', namespace)
if loc.text
]
logger.info(f"Found {len(urls)} URLs in sitemap")
# Crawl URLs
results = await self.crawl_urls(urls, max_concurrent=5)
except Exception as e:
logger.error(f"Sitemap crawling error: {e}")
finally:
await session.close()
return results
async def example_advanced():
"""Advanced crawler example"""
crawler = AdvancedWebCrawler(
user_agent="PoliteBot/1.0 (+http://example.com/bot)",
timeout=10
)
# Crawl with caching
url = "https://httpbin.org/html"
print("First request (no cache):")
result1 = await crawler.crawl_url_cached(url, use_cache=True)
print(f"Status: {result1.status_code}")
print("\nSecond request (from cache):")
result2 = await crawler.crawl_url_cached(url, use_cache=True)
print(f"Status: {result2.status_code}")
if __name__ == "__main__":
asyncio.run(example_advanced())
Key Features
-
Token Bucket Rate Limiting
- Per-domain rate limiting
- Async-safe implementation
- Smooth rate distribution
-
Robots.txt Parsing
- Automatic fetching and caching
- User-agent support
- Crawl delay extraction
-
Concurrent Crawling
- Multi-domain support
- Semaphore-based concurrency control
- Per-domain rate limiting
-
Politeness Policy
- Respects robots.txt
- User-Agent header
- Configurable delays
-
Error Handling
- Network errors
- Timeouts
- HTTP errors
-
BFS Domain Crawling
- Depth-limited crawling
- Link extraction
- Duplicate prevention
This implementation provides a production-ready web crawler with proper politeness and rate limiting!