Exercise: Web Crawler
The last exercise puts the chapter together, like the Go tour's web crawler.
You crawl a fake web: fetch(url) waits a moment, then returns the links on
that page. A page that doesn't exist has no links.
A good crawler:
- visits every page reachable from
start, includingstart - fetches each URL exactly once, even when many pages link to it
- fetches pages concurrently, but never more than
limitat the same time
You'll need asyncio.gather to fetch links concurrently, a set of seen URLs,
and asyncio.Semaphore(limit). A semaphore is a lock that lets up to limit
tasks in at once: async with sem:.
The trap is the same race as in the last lesson. Check whether a URL is seen
and mark it seen with no await in between, or two tasks can both decide to
fetch it.
Exercise: write crawl so it returns the set of all URLs it visited. Press
Check to run the tests.
This is a classic System design warm-up: "how would you crawl a site politely?"