Breadth first needs two pieces of state. Here is the whole crawl, one page at a time.
from collections import dequefrom collections.abc import Callablefrom urllib.parse import urldefrag, urljoin, urlparsedef 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 seencalls.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.
The crawl keeps two pieces of state:
The frontier: URLs you've found but haven't fetched yet.
The visited set, seen: every URL that has ever gone into the frontier.
Here they are after each fetch:
Step
Fetch
Frontier after
seen after
1
/
/a/b
//a/b
2
/a
/b/c
//a/b/c
3
/b
/c/broken
//a/b/c/broken
4
/c
/broken
no change
5
/broken
empty
no change: the fetch fails
/broken went into seen before its fetch failed. So it counts as reached even though it adds no links, which is the problem's rule for broken pages.
Get it right one page at a time first. The faster versions are this same loop with the fetches overlapped.
popleft takes the oldest URL, so the nearest pages come first
The frontier is a deque, open at both ends
frontier
oldestnextnewest/b/c/broken
popleft() takes the oldest, /b, so the nearest pages come first: breadth first. pop() would take the newest, /broken: depth first. append() adds new links at the right.
popleft() takes the oldest URL, so pages come out in order of distance from the start. That's breadth-first search. pop() would go depth-first.
Order starts to matter once there's a budget, like a page limit or a maximum depth. Then breadth-first gets you the pages nearest the start first.
Pick an answer above to see the rest
Predict
pop() instead of popleft(). What comes back?
A deque is a list that is fast at both ends. The name isn't the point: a plain list with pop(0) gives the same order, only slower on a big frontier.
In the editor, write visit_order(start, links, from_left): the order pages leave the frontier. Take them with popleft() when from_left is true and with pop() when it's false, and mark each page when you find it.
Pick an answer above to see the rest
Instructions
1
Write visit_order(start, links, from_left): the order pages are taken from the frontier, with popleft() when from_left is true and pop() when it's false. Mark a page when you find it.