KatInterview

Build a Same-Domain Web Page Crawler

Trees & GraphsModel answer
MediumModel answerTrees & Graphsgraph-traversalbfsdfs

Last 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:

  1. Choose either breadth-first or depth-first traversal and explain your choice
  2. Describe how you extract and compare hostnames from URLs
  3. Analyze time and space complexity
  4. Explain how you would handle network errors when getUrls fails

Constraints:

  • Your solution should be single-threaded
  • getUrls may 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?