Build a Same-Domain Web Page Crawler
Trees & GraphsModel answerLast updated
Write a crawler that visits all pages reachable from a start URL, staying within the same domain, avoiding cycles and duplicate fetches.
You're building a web crawler that explores pages on a single domain. Given a starting URL and a function that fetches all links from a page, your crawler should visit every reachable page that shares the same hostname as the starting URL.
Interface:
You have access to a function getUrls(url: str) -> List[str] that returns all hyperlinks found on the page at the given URL. This function performs the actual HTTP request.
Your task:
Implement a function that:
- Starts from
startUrl - Visits all pages reachable from it
- Only processes pages whose hostname exactly matches the hostname of
startUrl - Returns the set of all discovered URLs
- Avoids fetching the same page multiple times
- Handles cycles in the link graph
Additional requirements:
- Choose either breadth-first or depth-first traversal and explain your choice
- Describe how you extract and compare hostnames from URLs
- Analyze time and space complexity
- Explain how you would handle network errors when
getUrlsfails
Constraints:
- Your solution should be single-threaded
getUrlsmay raise exceptions for network failures- The web graph contains cycles
- Links may be absolute or relative URLs
- URLs may include ports, paths, query strings, and fragments
Example:
startUrl = "http://example.com/start"
Links found:
http://example.com/start -> ["http://example.com/about", "http://other.com/page"]
http://example.com/about -> ["http://example.com/contact", "http://example.com/start"]
http://example.com/contact -> []
Result: {"http://example.com/start", "http://example.com/about", "http://example.com/contact"}
Note that http://other.com/page is excluded (different hostname) and the cycle between start and about is handled correctly.
Hints
Hint 1
Think of the web as a directed graph where URLs are nodes and hyperlinks are edges. What graph traversal algorithm naturally fits this problem?
Hint 2
The hostname 'news.Example.com' and 'example.com' are different hosts. How do you extract and normalize hostnames correctly, handling ports and case-insensitivity?
Hint 3
To prevent infinite loops and duplicate work, mark URLs as visited at the right moment—when would marking too late cause problems?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Approach
This is a graph traversal problem. Each URL is a node, and each hyperlink creates a directed edge. We need to traverse from the starting node, following edges only to nodes that pass a hostname filter, while tracking visited nodes to handle cycles.
BFS vs DFS Choice
I'd use iterative breadth-first search (BFS) for these reasons:
Avoids stack depth issues: Link chains can be extremely deep (think pagination links going back years, or deeply nested category structures). Recursive DFS would hit Python's recursion limit (~1000 calls). While an iterative DFS with an explicit stack would also work, BFS is more conventional here.
Natural crawl ordering: BFS explores pages by distance from the start. Pages one link away are typically more important than pages buried deep in the site. If we later add a page limit or timeout, BFS gives us the most valuable subset.
Easier to extend: The queue-based structure maps cleanly to multi-threaded implementations with worker pools, a common follow-up question.
Hostname Extraction and Comparison
Don't parse URLs manually—use urllib.parse.urlsplit(url).hostname:
- Handles ports:
example.com:8080→example.com - Normalizes case:
Example.COM→example.com(hostnames are case-insensitive) - Strips authentication:
user:[email protected]→example.com - Returns
Nonefor non-HTTP URLs likemailto:
Important: "same hostname" means exact match. blog.example.com ≠ example.com. Don't use string suffix matching.
If libraries are forbidden, manually:
- Strip scheme (everything before
://) - Take content before first
/,?, or# - Remove
@prefix (userinfo) - Remove
:portsuffix - Lowercase the result
Cycle Detection
The key insight: mark URLs as visited when enqueued, not when dequeued.
If we waited until processing time:
- URL A links to B and C
- Both B and C link to D
- We'd enqueue D twice, fetching it twice
By marking immediately upon discovery, each URL enters the queue exactly once.
Complexity Analysis
Let V = number of same-domain pages reachable, E = total links encountered (including duplicates and off-domain).
Time: O(V + E)
- We process V pages (network calls dominate)
- We examine E links across all pages
- Each hostname check and set operation is O(1) amortized
- URL parsing is O(length), negligible compared to network I/O
Space: O(V)
visitedset stores at most V URLs- Queue contains at most V URLs
- Off-domain URLs are immediately filtered and never stored
Edge Cases and Normalization
Fragments: page.html#section1 and page.html#section2 are the same document. Strip fragments with urldefrag to avoid redundant fetches.
Relative links: URLs like /about or ../products must be resolved against the current page's URL using urljoin(current_url, link).
Self-links and cycles: Handled by the visited set.
Invalid URLs: Malformed URLs or non-HTTP schemes (mailto:, javascript:) should be skipped gracefully.
Ports and schemes: http://example.com and https://example.com have the same hostname per the spec. Same with example.com:8080. State this interpretation clearly.
Error Handling
Network operations fail. One broken page shouldn't stop the entire crawl.
Strategy:
- Wrap each
getUrlscall in try-except - Retry with exponential backoff for transient failures (2-3 attempts)
- On final failure, log the error and continue as if that page had no outgoing links
- Track failed URLs separately so callers can distinguish them
Design decision: A URL that failed to fetch was still discovered through a valid link, so it belongs in the result set. Return both discovered and failed sets.
Refinements to mention:
- Distinguish permanent errors (404) from transient (timeout, 503)
- Add per-request timeouts
- Implement a safety cap on total pages
- Respect robots.txt and rate limiting
Implementation
from collections import deque
from typing import Callable, List, Set, Tuple
from urllib.parse import urljoin, urldefrag, urlsplit
import logging
logger = logging.getLogger(__name__)
def extract_hostname(url: str) -> str:
"""Extract normalized hostname from URL, or None if invalid."""
try:
parsed = urlsplit(url)
if parsed.scheme not in ('http', 'https'):
return None
return parsed.hostname # already lowercased
except ValueError:
return None
def normalize_url(base_url: str, link: str) -> str:
"""Resolve relative URLs and strip fragments."""
absolute = urljoin(base_url, link.strip())
return urldefrag(absolute).url
def crawl(
startUrl: str,
getUrls: Callable[[str], List[str]],
max_retries: int = 2
) -> Tuple[Set[str], Set[str]]:
"""
Crawl all pages reachable from startUrl with matching hostname.
Returns:
(discovered_urls, failed_urls)
failed_urls is a subset of discovered_urls
"""
start = normalize_url(startUrl, startUrl)
target_hostname = extract_hostname(start)
if not target_hostname:
raise ValueError(f"Invalid start URL: {startUrl}")
visited = {start}
failed = set()
queue = deque([start])
while queue:
current_url = queue.popleft()
# Fetch with retry
links = None
for attempt in range(max_retries + 1):
try:
links = getUrls(current_url)
break
except Exception as e:
if attempt == max_retries:
logger.warning(f"Failed to fetch {current_url}: {e}")
failed.add(current_url)
break
# Exponential backoff
import time
time.sleep(0.1 * (2 ** attempt))
if links is None:
continue
# Process each link
for link in links:
if not link:
continue
# Normalize and check hostname
normalized = normalize_url(current_url, link)
link_hostname = extract_hostname(normalized)
if link_hostname != target_hostname:
continue
# Enqueue if not visited
if normalized not in visited:
visited.add(normalized)
queue.append(normalized)
return visited, failed
Common Mistakes
- Marking visited too late: Checking visited when dequeuing instead of when enqueuing causes duplicate fetches
- Substring hostname matching: Using
endswithtreats subdomains as matching - Ignoring fragments: Fetching the same page multiple times with different
#anchors - Recursive DFS: Hits stack limits on deep link chains
- Not handling relative URLs: Assumes all links are absolute
- Stopping on first error: One failed page shouldn't crash the crawler