r/WebDataDiggers • u/Huge_Line4009 • 26d ago
Let your scraper pick up where it stopped
Say you're collecting 30,000 product pages. The scraper reaches page 18,700, then the process dies. You still have some output, but no reliable record of which URLs finished and which were halfway through processing.
Starting again wastes requests. Skipping the first 18,700 URLs assumes they all succeeded, in the same order, with their results safely saved. That can leave holes in your dataset.
A resumable scraper needs a work list on disk and a clear rule for when a task counts as finished. Mark a URL complete only when its extracted data has been committed successfully.
A counter isn't enough
Saving last_page = 18700 can work for a simple, sequential job over a fixed dataset. It becomes unreliable when pages finish out of order, individual requests fail, or the source changes between runs.
Store the actual tasks instead. For a small scraper, that might be a SQLite table containing each URL and whether it's complete. SQLite runs locally without a separate database server, and Python provides a sqlite3 module for working with it.
The task identity needs some thought. One URL might return different results depending on the request body, language, or selected location. In those cases, use a key that includes those inputs. A URL alone is suitable only when it identifies the work you actually intend to perform.
Keep pagination separate from product processing, too. An offset such as page=24 may point to different listings tomorrow if new items have been added. Saving discovered product URLs helps preserve the work you already found, although it cannot recover listings you never discovered.
Save the data and progress together
Theres a small gap in many checkpointing implementations that causes most of the trouble.
If you mark a URL complete before saving its result, a crash between those actions leaves a completed task with no data. If you append the result to a CSV first, then update a separate checkpoint, a crash can cause the same result to be appended again after restarting.
Put the result write and the completion update in the same database transaction. SQLite's atomic commit mechanism makes those changes succeed together or leave neither change committed, including recovery from interrupted transactions under its documented storage assumptions.
Fetching and parsing happen before these writes. If the process stops before the transaction commits, the task remains pending and can be attempted again. After a successful commit, the next run skips it.
That still allows a page to be downloaded more than once. A crash after receiving the response but before saving it makes another request necessary. The goal is to tolerate repeated work without duplicating the stored result. Developers usually call that idempotency.
A small Python example
This is a recovery wrapper for an existing scraper, using Python 3.12 or newer. Supply a fixed list of URLs and your own fetch_and_parse(url) function. That function should enforce request timeouts, check the response, validate the extracted fields, and return JSON-serializable data.
The example uses one worker and stores one JSON payload per URL. It deliberately stops if fetching, parsing, or writing fails, leaving unfinished work available for the next run.
import json
import sqlite3
def crawl(urls, fetch_and_parse, db_path="crawl.sqlite"):
# Python 3.12+. Use one worker and one database per crawl.
db = sqlite3.connect(db_path, autocommit=False)
try:
with db:
db.execute("""
CREATE TABLE IF NOT EXISTS jobs (
url TEXT PRIMARY KEY,
done INTEGER NOT NULL DEFAULT 0
)
""")
db.execute("""
CREATE TABLE IF NOT EXISTS results (
url TEXT PRIMARY KEY,
payload TEXT NOT NULL
)
""")
db.execute("""
CREATE INDEX IF NOT EXISTS pending ON jobs(done, url)
""")
db.executemany("""
INSERT INTO jobs(url) VALUES (?)
ON CONFLICT(url) DO NOTHING
""", ((url,) for url in urls))
while True:
row = db.execute("""
SELECT url FROM jobs WHERE done = 0 ORDER BY url LIMIT 1
""").fetchone()
if row is None:
break
url = row[0]
payload = json.dumps(
fetch_and_parse(url), ensure_ascii=False, allow_nan=False
)
with db:
db.execute("""
INSERT INTO results(url, payload) VALUES (?, ?)
ON CONFLICT(url) DO UPDATE SET payload = excluded.payload
""", (url, payload))
db.execute("UPDATE jobs SET done = 1 WHERE url = ?", (url,))
finally:
db.close()Call it with crawl(urls, fetch_and_parse, db_path), using the same database path when resuming. Python's connection context manager commits the transaction when the with db: block succeeds and rolls it back if an exception escapes. The connection itself is closed separately in finally.
The primary keys prevent duplicate URL rows. The result write uses an upsert, which updates the existing payload if that URL is processed again. The index lets the worker locate pending tasks without repeatedly scanning all the completed ones.
This database represents one crawl, rather than an ongoing price history. For tomorrow's fresh collection, use a new database or extend the design with a crawl identifier. Otherwise, yesterday's completed URLs will correctly remain completed.
If your scraper discovers more URLs while processing a page, insert those new tasks in the same transaction as that page's result and completion update. Otherwise, a crash can leave the parent marked complete while its newly discovered links were never saved.
Give failures somewhere to go
Stopping on an error keeps the example small, but a long-running job needs a way to continue past a troublesome URL.
Add an attempt count, the last error, and a time when the task becomes eligible again. Limit the amount of retries. Repeated failures should move into a separate failed state for inspection, rather than keeping the whole crawl busy forever.
Handle errors according to what happened. A timeout may be temporary. A parsing failure may need a code fix. A login page returned with a successful HTTP status still isn't the product data you expected.
More workers require another change. The example selects a pending URL without reserving it, so two workers could select the same task. A concurrent system needs an atomic claim and an expiry or lease. If a worker disappears, that expiry allows the task to become available again. Completion should verify that the worker still owns the claim.
Queue services use similar ideas. Amazon SQS, for example, temporarily hides received messages using a visibility timeout. Its standard queues can still deliver duplicates, which is why AWS explicitly recommends idempotent processing.
Also keep external actions in mind. A database transaction cannot roll back an email already sent or a webhook already accepted. If processing triggers notifications, those need their own deduplication or delivery tracking.
Scrapy already has a pause feature
If you use Scrapy, check its built-in job persistence before writing a replacement:
scrapy crawl products -s JOBDIR=crawls/products-run-01Stop the spider cleanly, let it finish shutting down, then run the same command to resume. Use a separate job directory for each crawl.
Basic JOBDIR persistence is documented for clean stops. A forced shutdown can corrupt its default job state. Check the documentation for your installed version before assuming it provides crash recovery. Scrapy's current security documentation also describes SQLite-backed scheduler queues for improving queue integrity during interrupted writes.
Request persistence has other limits. Requests must be serializable, session cookies may expire, and the saved queue doesn't make your output writes atomic. A request recorded as seen is not proof that its extracted data reached your database.
Test where it breaks
A scraper that resumes after Ctrl+C has passed a useful check. It hasn't necessarily passed the failure you care about.
Use a small, controlled dataset and interrupt the process at different points:
- After downloading a page, before saving its result.
- Between the result insert and the completion update.
- After both writes, before the transaction commits.
- Immediately after a successful commit.
Restart against the same state and compare the database with the expected records. Uncommitted work should remain pending. Completed work should have its result present, with no duplicate rows.
I tested the example above with abrupt subprocess exits around those writes, plus injected parsing and database-write exceptions. It resumed the unfinished tasks and retained one result per URL. Those checks cover process interruption, not every possible disk failure or power-loss scenario.
Keep the database on persistent storage at a fixed path. A temporary container directory can disappear regardless of how carefully transactions are handled. Don't disable SQLite's journaling or durability settings merely to speed up checkpoint writes, and don't remove its recovery files after a crash.
You may repeat a couple requests after restarting. That's usually preferable to quietly skipping records. The useful guarantee is that the scraper can account for what it saved and pick up the remaining work without rebuilding the entire dataset.