Examining Requirements Closely
I've been drilling down on the user's objective and have confirmed that adhering to robots.txt is the main constraint. Now I'm meticulously identifying crucial Python libraries: requests for fetching pages, BeautifulSoup for parsing HTML, and urllib.parse for URL manipulation. My next step is to explore how to combine these tools.
Selecting the Tools
I've decided to proceed with requests for fetching, since it's straightforward for this use case. For parsing, BeautifulSoup remains the obvious choice, and urllib.parse will handle URL manipulation. To respect robots.txt, I'll utilize urllib.robotparser to avoid external dependencies. Additionally, I'll incorporate the time library to implement polite delays. I'm now structuring the crawler's overall logic.
Building the Core Logic
I'm now integrating the step-by-step process into code. I've got the import statements and a first draft of the can_fetch function, but realized that calling rp.read() every time is a performance bottleneck. That will need to be cached. I'm moving on to building a queue for links and writing the initial link-finding logic using BeautifulSoup.
Structuring the Class
I'm now focusing on a class-based approach. I've designed a PoliteCrawler class, with methods for initialization, fetching the robots.txt per domain, crawling, and respecting the delay. I've implemented a robots_cache to optimize repeated access to robots.txt files and am starting to structure the crawl loop.
Implementing the Crawler Loop
I'm now in the middle of structuring the crawl loop within the PoliteCrawler class. I have an internal frontier, implemented as a queue, and have added logic to skip visited URLs. The code ensures compliance with robots.txt before attempting to fetch a URL. I also integrated error handling for non-existent or inaccessible robots.txt files, defaulting to permitting if the file can't be found. Now I'm integrating the fetching logic within the crawler run loop, handling status codes.
Optimizing the Implementation
I'm currently polishing the code, incorporating detailed comments to improve readability. I've added a configurable User-Agent string to the crawler. Robust error handling for network requests, particularly for robots.txt fetching, is now in place. Finally, I've restricted the crawl to the starting domain, avoiding accidental crawling of the entire internet. This is shaping up nicely.
Assessing Limitations and Refinements
I'm now integrating the final pieces. I'm noting the trade-offs of this approach. It's a focused tutorial, but I need to highlight that Scrapy's industry standard and handles ROBOTSTXT_OBEY automatically. I'm also addressing memory concerns by adding a max_pages limit to avoid infinite loops, and I'm using urljoin to manage relative links. Finally, to keep the code simpler, I'll use a fixed limit_rate rather than complex Crawl-delay parsing.
Addressing Delays:
I'm now integrating an important detail. I've decided to mention in the comments that robots.txt can specify delay instructions and offer the user some links to learn about more complex delay implementations. I'll include a simple example, just to reinforce the point about Crawl-delay. Now I'm preparing to provide comprehensive instructions on how to install dependencies and run the final code, making sure everything is easily understandable for the user.
This is a complete, efficient, and polite web crawler using Python.
It uses the standard library urllib.robotparser to handle permissions and BeautifulSoup to parse the content.
Prerequisites
You will need to install requests and beautifulsoup4.
pip install requests beautifulsoup4
The Python Crawler Code
This script creates a class that caches the robots.txt file (so it doesn't download it for every single page request) and checks if your specific User-Agent is allowed to visit a URL before fetching it.
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlparse
from urllib.robotparser import RobotFileParser
import time
class PoliteCrawler:
def __init__(self, start_url, user_agent='MyPoliteBot/1.0', delay=1.0):
"""
:param start_url: The URL to begin crawling.
:param user_agent: The User-Agent string to identify your bot.
:param delay: Time in seconds to sleep between requests.
"""
self.start_url = start_url
self.user_agent = user_agent
self.delay = delay
# Keep track of visited URLs to avoid loops
self.visited = set()
# Queue of URLs to visit
self.queue = [start_url]
# Cache for robots.txt parsers (Domain -> RobotFileParser)
self.robots_cache = {}
def get_robot_parser(self, url):
"""
Fetches and caches the robots.txt for a specific domain.
"""
parsed_url = urlparse(url)
base_domain = f"{parsed_url.scheme}://{parsed_url.netloc}"
if base_domain in self.robots_cache:
return self.robots_cache[base_domain]
# Initialize parser
rp = RobotFileParser()
rp.set_url(urljoin(base_domain, '/robots.txt'))
try:
# Reads the robots.txt file from the network
rp.read()
except Exception:
# If robots.txt doesn't exist or fails, default policy usually applies.
# Here we set it to modified state to prevent crashing.
pass
self.robots_cache[base_domain] = rp
return rp
def is_allowed(self, url):
"""
Checks robots.txt to see if the URL is valid for this User Agent.
"""
try:
rp = self.get_robot_parser(url)
return rp.can_fetch(self.user_agent, url)
except Exception as e:
print(f"Error checking robots.txt for {url}: {e}")
return False
def crawl(self, max_pages=10):
"""
Main crawling loop.
"""
pages_crawled = 0
while self.queue and pages_crawled < max_pages:
url = self.queue.pop(0)
if url in self.visited:
continue
# 1. Check Robots.txt
if not self.is_allowed(url):
print(f"🚫 Blocked by robots.txt: {url}")
continue
# 2. Fetch the Page
try:
print(f"🕷️ Crawling: {url}")
headers = {'User-Agent': self.user_agent}
response = requests.get(url, headers=headers, timeout=5)
if response.status_code != 200:
print(f"⚠️ Status {response.status_code} for {url}")
continue
except requests.RequestException as e:
print(f"❌ Network error: {e}")
continue
# 3. Mark as visited
self.visited.add(url)
pages_crawled += 1
# 4. Parse Content
soup = BeautifulSoup(response.text, 'html.parser')
# Example: Print the page title
page_title = soup.title.string.strip() if soup.title else "No Title"
print(f" 📄 Title: {page_title}")
# 5. Find and Queue new Links
for link in soup.find_all('a', href=True):
raw_link = link['href']
absolute_link = urljoin(url, raw_link)
# IMPORTANT: Filter to keep crawler on the same domain
# Remove this check if you want to crawl external sites (Use caution)
if urlparse(absolute_link).netloc == urlparse(self.start_url).netloc:
if absolute_link not in self.visited and absolute_link not in self.queue:
self.queue.append(absolute_link)
# 6. Be Polite (Sleep)
time.sleep(self.delay)
print(f"\n✅ Finished. Crawled {pages_crawled} pages.")
# --- Usage ---
if __name__ == "__main__":
# Replace with a site you are allowed to crawl (e.g., your own site or a test site)
# https://books.toscrape.com is a popular sandbox for scraping testing.
crawler = PoliteCrawler(start_url="https://books.toscrape.com")
crawler.crawl(max_pages=5)
How it works
urllib.robotparser: This is a standard Python library. It reads a robots.txt file (e.g., http://example.com/robots.txt), parses the rules (Allow/Disallow), and provides the .can_fetch() method.
- Caching: The
robots_cache dictionary ensures we download the robots.txt file only once per domain. Without this, the script would request robots.txt before every single page request, which is inefficient and could get you banned.
- User-Agent: Websites use this string to identify who is crawling them. I set it to
'MyPoliteBot/1.0'.
- Politeness Delay: The
time.sleep(self.delay) ensures we don't hammer the server with requests instantly. This is crucial for ethical crawling.
- Domain Restriction: Inside step 5, there is a check
urlparse(absolute_link).netloc == .... This keeps the crawler inside the website you started on so it doesn't drift off to crawl the entire internet.
Alternative: Scrapy
If you intend to build a large-scale production crawler, I highly recommend using Scrapy instead of writing your own script. Scrapy handles robots.txt, concurrency, throttling, and retry logic automatically.
To enable robots.txt in Scrapy, you simply set one line in settings.py:
ROBOTSTXT_OBEY = True