6/28
Part 2 of 6 · Breadth firstLearn and do

Keep two things: a frontier and a visited set

Breadth first needs two pieces of state. Here is the whole crawl, one page at a time.

from collections import deque
from collections.abc import Callable
from urllib.parse import urldefrag, urljoin, urlparse


def crawl_one_at_a_time(
    start_url: str, fetch: Callable[[str], list[str]]
) -> set[str]:
    """Every reachable page on the start's host, one fetch at a time."""
    start = urldefrag(start_url).url
    host = urlparse(start).hostname
    seen, frontier = {start}, deque([start])
    while frontier:
        url = frontier.popleft()
        try:
            links = fetch(url)
        except Exception:
            continue
        for link in links:
            link = urldefrag(urljoin(url, link)).url
            if urlparse(link).hostname == host and link not in seen:
                seen.add(link)
                frontier.append(link)
    return seen


calls.clear()
found = crawl_one_at_a_time(f"{E}/", fetch)
print(*calls, sep="\n")
print(len(found), "pages found")
Predict

Which pages get fetched, and in what order?

Pick one to see what it prints.
Pick an answer above to see the rest
Predict

pop() instead of popleft(). What comes back?

Pick an answer above to see the rest