Building a web crawler in Python
The user is asking for a Python web crawler that respects robots.txt. They likely want both the code and an explanation. I should confirm their level of understanding, aiming for a concise yet informative response.
I’ll create a script that uses common libraries like urllib and BeautifulSoup. The crawler will read robots.txt to obey disallow rules and crawl-delay requirements, while ensuring ethical guidelines are followed to avoid issues like DOS attacks. I’ll provide a minimal but functional example, detailing each step of the process.Refining the web crawler approach
I’m simplifying the approach for how to read robots.txt using requests to parse the lines. While RobotFileParser doesn’t have a method for crawl-delay, I can guide how to handle it. Although it’s important to respect allow/disallow rules, I’ll mention crawl-delay and suggest parsing it manually with regular expressions.
Since the user didn’t specify a domain, I’ll create a general script where you can pass in the start_url. I’ll emphasize max_pages or max_depth limitations and remind about politeness and not circumventing robots.txt, as it’s advisory and not always present. A simple crawler for the same domain should be benign!Designing the web crawler script
I’m going to outline the script's design, starting with importing necessary libraries like requests, urljoin, and BeautifulSoup. I will create a class called RobotsHandler that uses RobotFileParser while also manually handling crawl-delay.
In the __init__ method, I’ll set up the base URL and user agent, read the robots.txt file, and implement a method to fetch crawl-delay. This will include checking the lines for the correct user-agent, and parsing the float value for the delay. I’ll simplify this by focusing on the first matching rule.Building the Crawler class
Next, I’ll create the Crawler class, setting up parameters like start_url, user_agent, max_pages, and max_depth. In the crawl() method, I’ll implement a breadth-first search (BFS) with a queue containing (url, depth) and a set for visited URLs.
I’ll ensure the crawler respects the robots.txt rules by checking if it can fetch a URL. I'll enforce limitations on the pages crawled, enforce time delays, and ensure proper handling of HTML fetching and parsing with BeautifulSoup. Lastly, I'll remind the user about installing necessary packages with pip!Addressing robots.txt handling and disclaimers
I need to ensure that our crawler handles the absence of robots.txt properly; when rp.read() encounters a 404 error, it defaults to allowing everything. That’s important to note! I should also include disclaimers about abiding by terms of service and laws, testing responsibly, and avoiding server overload.
Finally, I’ll craft the complete answer, including the code in Markdown, to present a neat and organized response for the user. This way, it’s both informative and user-friendly! Below is a small, self‑contained Python web crawler that:
- Respects
robots.txt (Allow/Disallow via urllib.robotparser)
- Tries to honor
Crawl-delay (parsed manually)
- Stays within one domain
- Uses a polite delay and a page/depth limit
You can use it as a starting point and extend as needed.
Requirements
pip install requests beautifulsoup4
crawler.py
import time
import re
import requests
from collections import deque
from urllib.parse import urljoin, urlparse, urldefrag
from urllib.robotparser import RobotFileParser
from bs4 import BeautifulSoup
class RobotsPolicy:
"""Handles robots.txt rules + crawl-delay for a given site."""
def __init__(self, base_url: str, user_agent: str, default_delay: float = 1.0):
self.base_url = base_url
self.user_agent = user_agent
self.default_delay = default_delay
self.rp = RobotFileParser()
self.crawl_delay = default_delay
parsed = urlparse(base_url)
robots_url = f"{parsed.scheme}://{parsed.netloc}/robots.txt"
# Set up RobotFileParser for allow/disallow and read it
self.rp.set_url(robots_url)
try:
self.rp.read()
except Exception:
# If robots can't be read, default to allowing (like RobotFileParser does)
pass
# Try to parse crawl-delay manually
self.crawl_delay = self._parse_crawl_delay(robots_url) or default_delay
def can_fetch(self, url: str) -> bool:
return self.rp.can_fetch(self.user_agent, url)
def _parse_crawl_delay(self, robots_url: str):
"""Attempt to parse crawl-delay from robots.txt for our UA or *."""
try:
resp = requests.get(
robots_url,
headers={"User-Agent": self.user_agent},
timeout=5,
)
except Exception:
return None
if resp.status_code != 200 or not resp.text:
return None
lines = resp.text.splitlines()
current_ua = None
applicable = False
delay = None
# Simple state machine over robots.txt
for raw_line in lines:
line = raw_line.strip()
if not line or line.startswith("#"):
continue
# user-agent: ...
m_ua = re.match(r"(?i)^user-agent:\s*(.+)$", line)
if m_ua:
current_ua = m_ua.group(1).strip()
# Section is applicable if UA matches us or '*' (later ones can override earlier)
if current_ua == "*" or current_ua.lower() in self.user_agent.lower():
applicable = True
else:
applicable = False
continue
if not applicable:
continue
# crawl-delay: ...
m_cd = re.match(r"(?i)^crawl-delay:\s*([0-9.]+)$", line)
if m_cd:
try:
delay = float(m_cd.group(1))
except ValueError:
pass
return delay
class Crawler:
"""Simple breadth-first crawler that respects robots.txt."""
def __init__(self, start_url: str, user_agent: str, max_pages: int = 50, max_depth: int = 2):
self.start_url = start_url
self.user_agent = user_agent
self.max_pages = max_pages
self.max_depth = max_depth
parsed = urlparse(start_url)
self.scheme = parsed.scheme
self.domain = parsed.netloc
self.robots = RobotsPolicy(start_url, user_agent)
self.visited = set()
self.last_fetch_time = 0.0
def crawl(self):
queue = deque()
queue.append((self.start_url, 0))
pages_crawled = 0
print(f"Starting crawl at: {self.start_url}")
print(f"User-Agent: {self.user_agent}")
print(f"Robots crawl-delay: {self.robots.crawl_delay} seconds")
print()
while queue and pages_crawled < self.max_pages:
url, depth = queue.popleft()
# Normalize URL (strip fragment)
url = urldefrag(url)[0]
if url in self.visited:
continue
self.visited.add(url)
if depth > self.max_depth:
continue
# Stay within same domain
if urlparse(url).netloc != self.domain:
continue
# Check robots.txt
if not self.robots.can_fetch(url):
print(f"[robots.txt] Disallowed: {url}")
continue
# Politeness delay (per host)
self._respect_delay()
try:
resp = requests.get(
url,
headers={"User-Agent": self.user_agent},
timeout=10,
)
self.last_fetch_time = time.time()
except requests.RequestException as e:
print(f"[error] Failed to fetch {url}: {e}")
continue
content_type = resp.headers.get("Content-Type", "")
if "text/html" not in content_type:
print(f"[skip] Non-HTML content at {url} ({content_type})")
continue
if resp.status_code != 200:
print(f"[skip] Status {resp.status_code} at {url}")
continue
pages_crawled += 1
print(f"[{pages_crawled}] Visited: {url} (depth={depth})")
# Parse links and enqueue
soup = BeautifulSoup(resp.text, "html.parser")
for a in soup.find_all("a", href=True):
href = a["href"].strip()
# Build absolute URL
next_url = urljoin(url, href)
next_url = urldefrag(next_url)[0]
if next_url not in self.visited:
queue.append((next_url, depth + 1))
print("\nCrawl finished.")
print(f"Total pages visited: {pages_crawled}")
def _respect_delay(self):
"""Sleep if necessary to respect crawl-delay."""
delay = self.robots.crawl_delay
now = time.time()
elapsed = now - self.last_fetch_time
if elapsed < delay:
time.sleep(delay - elapsed)
if __name__ == "__main__":
# Example usage
start_url = "https://example.com/"
user_agent = "MyRespectfulCrawler/1.0 (+https://example.com/bot-info)"
crawler = Crawler(
start_url=start_url,
user_agent=user_agent,
max_pages=20, # limit number of pages
max_depth=2, # limit depth from start_url
)
crawler.crawl()
How to run
- Save as
crawler.py.
- Edit
start_url and user_agent in the __main__ block.
- Run:
python crawler.py
Notes / Good practice
- Always use a descriptive
User-Agent with contact or info URL.
- Keep
max_pages and max_depth conservative when testing.
- Respect the target site’s terms of service and legal requirements.
- Consider adding:
- Logging to file
- Persistent storage of crawled data
- Parallelization with per-host rate limiting (requires more careful politeness handling)
If you tell me what you want to do with the crawled pages (e.g., indexing, scraping specific content), I can adapt this crawler to store or process data accordingly.