#!/usr/bin/env python3 """A small Python web crawler: requests, a queue (breadth first) and the standard library's HTML parser. Starts from one URL, stays on its host, reads each URL once, follows links until MAX_PAGES, honours robots.txt and waits between requests. Writes every URL with its status and title to pages.csv. pip install requests python3 crawler.py """ import csv import time from collections import deque from html.parser import HTMLParser from urllib import robotparser from urllib.parse import urldefrag, urljoin, urlparse import requests START = "https://books.toscrape.com/" MAX_PAGES = 50 DELAY = 0.5 # seconds between two requests: be polite AGENT = "my-crawler/1.0" class PageParser(HTMLParser): """Collects the links and the of one HTML page.""" def __init__(self): super().__init__() self.links, self.title, self._in_title = [], "", False def handle_starttag(self, tag, attrs): if tag == "a" and dict(attrs).get("href"): self.links.append(dict(attrs)["href"]) elif tag == "title": self._in_title = True def handle_endtag(self, tag): if tag == "title": self._in_title = False def handle_data(self, data): if self._in_title: self.title += data host = urlparse(START).netloc robots = robotparser.RobotFileParser(urljoin(START, "/robots.txt")) robots.read() http = requests.Session() http.headers["User-Agent"] = AGENT queue, seen, rows = deque([START]), {START}, [] started = time.time() while queue and len(rows) < MAX_PAGES: url = queue.popleft() if not robots.can_fetch(AGENT, url): rows.append([url, "robots.txt", ""]) continue try: response = http.get(url, timeout=30) except requests.RequestException as err: rows.append([url, type(err).__name__, ""]) continue page = PageParser() if "html" in response.headers.get("Content-Type", ""): page.feed(response.text) rows.append([url, response.status_code, " ".join(page.title.split())]) for href in page.links: link = urldefrag(urljoin(url, href)).url # absolute, without #fragment if urlparse(link).netloc == host and link not in seen: seen.add(link) queue.append(link) time.sleep(DELAY) with open("pages.csv", "w", newline="") as f: csv.writer(f).writerows([["url", "status", "title"], *rows]) print(f"{len(rows)} pages in {time.time() - started:.0f} s; {len(queue)} URLs still in the queue")