import requests
from bs4 import BeautifulSoup
from urllib.robotparser import RobotFileParser
from urllib.parse import urljoin, urlparse
import time
from collections import deque
import threading
from concurrent.futures import ThreadPoolExecutor
class RespectfulCrawler:
"""
A polite Python web crawler that:
- Respects robots.txt for each domain.
- Crawls only within the starting domain.
- Uses BFS with a queue.
- Implements rate limiting (delay between requests).
- Supports multi-threading for efficiency (optional).
- Logs visited URLs and errors.
- Extracts and follows <a> links.
Usage:
crawler = RespectfulCrawler('https://example.com', max_pages=100, delay=1.0, num_threads=5)
crawler.crawl()
print(f"Visited {len(crawler.visited)} pages")
print("Sample content:", list(crawler.visited)[:5])
"""
def __init__(self, start_url, max_pages=1000, delay=1.0, num_threads=1, user_agent='SherlockCrawler/1.0 (by Trailblazer Labs)'):
self.start_url = start_url
self.max_pages = max_pages
self.delay = delay
self.num_threads = num_threads
self.user_agent = user_agent
self.visited = set()
self.queue = deque([start_url])
self.domain = urlparse(start_url).netloc
self.robot_parsers = {} # Cache per-domain robots.txt parsers
self.lock = threading.Lock() # For thread-safe operations
def _get_robot_parser(self, domain):
"""Fetch and cache RobotFileParser for a domain."""
if domain in self.robot_parsers:
return self.robot_parsers[domain]
rp = RobotFileParser()
# Construct robots.txt URL
parsed_start = urlparse(self.start_url)
base_url = f"{parsed_start.scheme}://{domain}/robots.txt"
try:
rp.set_url(base_url)
rp.read()
print(f"Loaded robots.txt from {base_url}")
except Exception as e:
print(f"Could not load robots.txt from {base_url}: {e}. Proceeding cautiously.")
with self.lock:
self.robot_parsers[domain] = rp
return rp
def can_fetch(self, url):
"""Check if we can fetch the URL per robots.txt."""
parsed = urlparse(url)
domain = parsed.netloc
rp = self._get_robot_parser(domain)
return rp.can_fetch(self.user_agent, url)
def _crawl_single(self, url):
"""Crawl a single URL (thread-safe)."""
with self.lock:
if url in self.visited or len(self.visited) >= self.max_pages:
return
if not self.can_fetch(url):
print(f"Blocked by robots.txt: {url}")
return
try:
headers = {'User-Agent': self.user_agent}
resp = requests.get(url, headers=headers, timeout=10)
resp.raise_for_status()
with self.lock:
self.visited.add(url)
print(f"Crawled ({len(self.visited)}/{self.max_pages}): {url}")
# Parse and enqueue links (same domain only)
soup = BeautifulSoup(resp.text, 'html.parser')
for link in soup.find_all('a', href=True):
href = link['href'].strip()
if href.startswith('#') or href.startswith('javascript:'):
continue
full_url = urljoin(url, href)
parsed_link = urlparse(full_url)
# Same domain only
if (parsed_link.netloc == self.domain and
full_url not in self.visited and
len(self.visited) < self.max_pages):
with self.lock:
self.queue.append(full_url)
except Exception as e:
print(f"Error crawling {url}: {e}")
time.sleep(self.delay)
def crawl(self):
"""Start the crawl (single-threaded or multi-threaded)."""
print(f"Starting crawl from {self.start_url} (domain: {self.domain})")
print(f"Max pages: {self.max_pages}, Delay: {self.delay}s, Threads: {self.num_threads}")
if self.num_threads == 1:
# Single-threaded
while self.queue and len(self.visited) < self.max_pages:
url = self.queue.popleft()
self._crawl_single(url)
else:
# Multi-threaded
with ThreadPoolExecutor(max_workers=self.num_threads) as executor:
while self.queue and len(self.visited) < self.max_pages:
batch = []
for _ in range(min(self.num_threads, len(self.queue))):
if self.queue:
batch.append(self.queue.popleft())
futures = [executor.submit(self._crawl_single, url) for url in batch]
for future in futures:
future.result() # Wait for batch
print(f"\nCrawl complete! Visited {len(self.visited)} pages.")
return self.visited
# Example usage
if __name__ == "__main__":
# Install dependencies: pip install requests beautifulsoup4
crawler = RespectfulCrawler(
start_url='https://example.com',
max_pages=50,
delay=0.5,
num_threads=3
)
visited_urls = crawler.crawl()
# Optional: Save to file
with open('crawled_urls.txt', 'w') as f:
for url in sorted(visited_urls):
f.write(url + '\n')
print("URLs saved to crawled_urls.txt")
Key Features:
- Robots.txt Respect: Uses
urllib.robotparser to check permissions per domain (cached for efficiency). Skips disallowed URLs.
- Domain-Limited: Only follows links within the starting domain to avoid sprawling.
- Polite: Configurable delay between requests; respectful User-Agent.
- Efficient: BFS queue, visited set to avoid duplicates, optional multi-threading.
- Robust: Handles errors gracefully (timeouts, 4xx/5xx), skips noindex/nofollow implicitly via robots.txt.
- Extensible: Easy to add content extraction (e.g., save
resp.text to files).
- Thread-Safe: Locks for shared state in multi-threaded mode.
Setup:
pip install requests beautifulsoup4
- Run the script – it crawls
example.com by default.
- Customize
start_url, max_pages, etc.
This crawler is production-ready for ethical scraping. Always check the site's terms! 🚀