Providing complete asyncio crawler code
Here's a Python asyncio-based web crawler demonstrating per-domain token bucket rate limiting at 1 request/sec, robots.txt parsing via urllib.robotparser fed from aiohttp-fetched content, and concurrency across multiple domains.
Here's a self‑contained example of an asyncio‑based crawler that:
- Uses
urllib.robotparser to load and check robots.txt rules.
- Maintains a per‑domain token bucket to enforce at most one request per second to any given domain.
- Can crawl multiple domains concurrently.
This code uses aiohttp for asynchronous HTTP and a simple queue to manage crawl tasks:
import asyncio
import time
import urllib.parse
import urllib.robotparser
from typing import Dict, Set, Optional
import aiohttp
class TokenBucket:
"""
A simple token bucket that refills at `rate` tokens per second up to `capacity`.
Call `await acquire()` before sending a request; it will sleep if no token is available.
"""
def __init__(self, rate: float = 1.0, capacity: int = 1):
self.rate = rate
self.capacity = capacity
self.tokens = capacity
self.updated_at = time.monotonic()
self._lock = asyncio.Lock()
async def acquire(self):
while True:
async with self._lock:
now = time.monotonic()
elapsed = now - self.updated_at
# Refill tokens
self.tokens = min(self.capacity, self.tokens + elapsed * self.rate)
self.updated_at = now
if self.tokens >= 1:
self.tokens -= 1
return # Got a token, proceed with the request
# Not enough tokens; compute wait time
wait_for = (1 - self.tokens) / self.rate
# Sleep outside the lock
await asyncio.sleep(wait_for)
class Crawler:
def __init__(self, user_agent: str = "MyAsyncCrawler/1.0", max_tasks: int = 10):
self.user_agent = user_agent
self.max_tasks = max_tasks
self.session: Optional[aiohttp.ClientSession] = None
self.buckets: Dict[str, TokenBucket] = {} # domain -> token bucket
self.robots: Dict[str, urllib.robotparser.RobotFileParser] = {} # domain -> parser
self.seen: Set[str] = set()
def _get_domain(self, url: str) -> str:
return urllib.parse.urlparse(url).netloc
def _get_bucket(self, domain: str) -> TokenBucket:
# Ensure each domain has its own rate limiter
if domain not in self.buckets:
self.buckets[domain] = TokenBucket(rate=1.0, capacity=1) # 1 req per second
return self.buckets[domain]
async def _fetch_robots(self, domain: str):
"""Fetch and parse robots.txt for a domain, storing the robotparser."""
if domain in self.robots:
return self.robots[domain]
rp = urllib.robotparser.RobotFileParser()
robots_url = f"http://{domain}/robots.txt"
# Use token bucket to respect rate limit for robots.txt fetch as well
bucket = self._get_bucket(domain)
await bucket.acquire()
try:
async with self.session.get(robots_url, headers={"User-Agent": self.user_agent}) as resp:
if resp.status == 200:
text = await resp.text()
rp.parse(text.splitlines())
else:
# If no robots.txt or error, default to allow
rp.parse([])
except Exception:
# On failure, default to allow
rp.parse([])
# Cache parser
self.robots[domain] = rp
return rp
async def fetch(self, url: str) -> Optional[str]:
"""
Fetch a URL respecting the per-domain rate limit and robots.txt.
Returns the response text, or None if disallowed or failed.
"""
domain = self._get_domain(url)
rp = await self._fetch_robots(domain)
if not rp.can_fetch(self.user_agent, url):
print(f"Disallowed by robots.txt: {url}")
return None
bucket = self._get_bucket(domain)
await bucket.acquire()
try:
async with self.session.get(url, headers={"User-Agent": self.user_agent}) as resp:
if resp.status == 200 and resp.content_type == "text/html":
return await resp.text()
else:
print(f"Failed to fetch {url}: status {resp.status}")
except Exception as e:
print(f"Error fetching {url}: {e}")
return None
async def crawl(self, start_urls, max_depth=1):
"""
Breadth-first crawl starting from start_urls up to max_depth.
"""
queue = asyncio.Queue()
for u in start_urls:
await queue.put((u, 0))
self.session = aiohttp.ClientSession()
async def worker():
while True:
try:
url, depth = queue.get_nowait()
except asyncio.QueueEmpty:
break
if url in self.seen or depth > max_depth:
queue.task_done()
continue
self.seen.add(url)
html = await self.fetch(url)
queue.task_done()
# Simple link extraction (not robust), just to demonstrate enqueuing.
if html and depth < max_depth:
for link in self._extract_links(html, url):
if link not in self.seen:
await queue.put((link, depth + 1))
tasks = [asyncio.create_task(worker()) for _ in range(self.max_tasks)]
await queue.join()
for t in tasks:
t.cancel()
await self.session.close()
def _extract_links(self, html: str, base_url: str) -> Set[str]:
"""
Extract absolute links from the HTML using a simple regex-free approach.
For demo purposes; consider using BeautifulSoup or lxml for robustness.
"""
links = set()
for token in html.split():
if 'href="' in token:
start = token.find('href="') + 6
end = token.find('"', start)
href = token[start:end]
if href.startswith("#") or href.startswith("mailto:"):
continue
absolute = urllib.parse.urljoin(base_url, href)
links.add(absolute)
return links
if __name__ == "__main__":
start = ["https://example.com/", "https://httpbin.org/"]
crawler = Crawler(user_agent="MyAsyncCrawler/1.0", max_tasks=5)
asyncio.run(crawler.crawl(start_urls=start, max_depth=1))
Key points:
-
TokenBucket.acquire() enforces the “no more than 1 request per second” rule for each domain by sleeping when necessary. Because each domain gets its own TokenBucket instance (self.buckets[domain]), concurrent tasks hitting different domains can proceed in parallel without violating per‑domain politeness.
-
urllib.robotparser is used to parse robots.txt (_fetch_robots). Before fetching any page, the crawler checks rp.can_fetch(...) to respect robots exclusions.
-
The crawler uses an asyncio Queue and a small pool of worker tasks to achieve concurrency.
This is a minimal example to illustrate the pattern; in a production crawler you would want more robust HTML parsing, better URL normalization, error handling, and persistence of crawl state.