Sub topic 2
Avoiding Repeat Visits with a Seen Set
Assume you know basic HTTP, HTML links, Python sets, queues, and heaps. This chapter connects URL deduplication to a polite crawl frontier.
Track each normalized URL once
A crawler discovers the same page through many links. Normalize each URL before adding it to a seen set. The set gives average constant-time membership checks.
Mark a URL as seen when you enqueue it, not when you fetch it. Otherwise, several discovered links can queue the same URL before the first request finishes.
from collections import defaultdict, deque
import heapq
import time
from urllib.parse import urlsplit
class Frontier:
def __init__(self, delay=1.0):
self.delay = delay
self.queues = defaultdict(deque)
self.next_time = {}
self.ready = []
self.seen = set()
def add(self, url):
if url in self.seen:
return False
self.seen.add(url)
host = urlsplit(url).netloc
was_empty = not self.queues[host]
self.queues[host].append(url)
if was_empty:
heapq.heappush(
self.ready, (self.next_time.get(host, 0.0), host)
)
return True
def next(self):
if not self.ready:
return None
available, host = heapq.heappop(self.ready)
wait = available - time.monotonic()
if wait > 0:
time.sleep(wait)
url = self.queues[host].popleft()
self.next_time[host] = time.monotonic() + self.delay
if self.queues[host]:
heapq.heappush(self.ready, (self.next_time[host], host))
return url
frontier = Frontier(delay=1.0)
frontier.add("https://example.com/")
frontier.add("https://example.com/") # ignored
print(frontier.next())Design the URL frontier
The frontier is the collection of URLs waiting to be fetched. Keep a separate FIFO queue for each host. A heap orders hosts by the next time they may be contacted. This prevents one busy host from blocking every other host.
Respect robots.txt
Before fetching a host, read its robots.txt and cache the result. Use the crawler's user-agent name when checking permission.
Apply politeness and handle failures
Enforce delays per host, not globally. After a request, schedule that host for a later time. Set connection and read timeouts. Retry only temporary failures such as 429 or selected 5xx responses, with exponential backoff. Do not retry permanent 4xx responses repeatedly. Cap retries, response size, and redirect count. Skip non-HTML content when the crawler only indexes pages.
Exercise
Why should a crawler add a URL to the seen set before fetching it?
Show answer
It prevents duplicate queue entries when several pages discover the URL before its first fetch completes.