import hashlib
import json
import os
import sqlite3
from datetime import datetime, timezone
from urllib.parse import urljoin, urlsplit
import requests
from bs4 import BeautifulSoup
SEED ='https://books.toscrape.com/catalogue/page-48.html'LIMIT =2DB = os.environ.get('PAGINATION_DB','books.sqlite')defallowed(url): parts = urlsplit(url)return parts.scheme =='https'and parts.netloc =='books.toscrape.com'with sqlite3.connect(DB)as db, requests.Session()as session: db.execute('CREATE TABLE IF NOT EXISTS records (url TEXT PRIMARY KEY, title TEXT, observed_at TEXT)') db.execute('CREATE TABLE IF NOT EXISTS state (id INTEGER PRIMARY KEY, next_url TEXT)') db.execute('CREATE TABLE IF NOT EXISTS pages (fingerprint TEXT PRIMARY KEY, url TEXT)') db.execute('INSERT OR IGNORE INTO state VALUES (1, ?)',(SEED,)) db.commit() visited =0while visited < LIMIT: current = db.execute('SELECT next_url FROM state WHERE id=1').fetchone()[0]if current isNone:breakifnot allowed(current):raise ValueError('Next URL left the allowed origin') response = session.get(current, timeout=(10,30), allow_redirects=False) response.raise_for_status()if response.status_code !=200:raise ValueError('Unexpected page status; review redirect or response') soup = BeautifulSoup(response.content,'html.parser') cards = soup.select('article.product_pod h3 a')ifnot cards:raise ValueError('No product cards; do not advance checkpoint') rows =[(urljoin(current, c['href']), c.get('title','').strip())for c in cards]ifany(not title ornot allowed(url)for url, title in rows):raise ValueError('Invalid product record') fingerprint = hashlib.sha256('\n'.join(sorted(url for url, _ in rows)).encode()).hexdigest()if db.execute('SELECT 1 FROM pages WHERE fingerprint=?',(fingerprint,)).fetchone():raise ValueError('Repeated page content; review pagination before continuing') link = soup.select_one('li.next a') next_url = urljoin(current, link['href'])if link elseNoneif next_url isnotNoneandnot allowed(next_url):raise ValueError('Next URL left the allowed origin') observed = datetime.now(timezone.utc).isoformat()with db: db.executemany('INSERT OR REPLACE INTO records VALUES (?, ?, ?)',[(u, t, observed)for u, t in rows]) db.execute('INSERT INTO pages VALUES (?, ?)',(fingerprint, current)) db.execute('UPDATE state SET next_url=? WHERE id=1',(next_url,)) visited +=1 next_url = db.execute('SELECT next_url FROM state WHERE id=1').fetchone()[0]print(json.dumps({'pages_this_run': visited,'records_total': db.execute('SELECT COUNT(*) FROM records').fetchone()[0],'next_url': next_url,'complete': next_url isNone}))
Start a crawl of https://quotes.toscrape.com/ with maxPages=2
and maxDepth=1. Retrieve Markdown and links. Keep the returned
crawl ID and query that existing task until it reaches a terminal
state. Retrieve its page results and read every available Markdown
reference. Report discovered URLs, completed pages, failed pages,
and whether the available records cover my requested scope.
Do not resubmit the crawl while checking its progress.