To stop on a bad run, have the script count the rows it just saved, count the rows in the file from the last good run, and compare the two before it touches that file. When the new count has fallen by more than half, the script exits with an error code and leaves the last good file alone.
At the end of this lesson you have runs/latest.csv, a file that holds the newest run that passed the check, and a stop_bad_run.py that exits 2 when a run comes back too small. You will cut one run short on purpose and watch latest.csv keep its 20 rows.
A short run that looks like success
Lesson 11 left you with run_log.py. It crawls up to 20 pages, writes them to a CSV file named after the start time, and adds a line to runs/log.txt. It exits 1 when a page answers something other than 200.
It has no opinion about a run where every page answered 200 and there were only five of them. A crawl that comes back with a quarter of the usual pages looks like success to that script.
A file that only good runs may replace
Lesson 10 gave each run a file named after its start time, so a later run does not write over an earlier one's rows. The recorded script below is weaker on that point than yours. It names files to the second and opens them in w mode, so two runs started in the same second would share a name and the later one would overwrite the earlier. The x mode you kept from lesson 10 refuses to open a file that already exists. A program that reads your data still has to know which file to trust, and latest.csv is that file. Every run writes its dated file. A run that passes the check is then copied over latest.csv, and a run that fails is not.
The copy is one call to shutil.copyfile. Python's documentation for that function says "If dst already exists, it will be replaced." So the script has to decide before it calls. Once the call runs, the old rows are gone.
The script counts the lines in latest.csv, takes one off for the header, and calls the result before. On the first run there is no such file, before is 0, and any run that answered 200 on every page passes.
What stop_bad_run.py adds
These are the lines that are new since lesson 11's recorded script:
- A
LATESTconstant and acount_rows()function, which returns 0 when the file does not exist. import shutil, for the copy.- An optional
--shortargument that lowers thelimitthe script sends from 20 to 5. It exists so you can produce a small run whenever you want one. - After the dated file is written, the script reads
before, works outwhole, and copies the dated file overlatest.csvonly whenwholeis true. - The log line now ends in
okorheld, and a held run returns 2.
The recorded script holds a run that has under 80 percent of the earlier rows. You will loosen that to half in a moment. It also builds on the first version of lesson 11's log, with the plain one-line write, so the edit below shows where the check goes in the main() you finished that lesson with.
The key comes from the SPIDER_API_KEY environment variable. Here is the script as it ran twice on 2026-11-20, under Python 3.14.7:
"""Crawl a site through the Spider API, save the run, and replace runs/latest.csv only when
the run looks whole.
python3 stop_bad_run.py URL [--short]
--short lowers the page limit to 5, to show what a cut-off run does.
A run looks whole when every page answered 200 and it has at least 80 percent of the rows
latest.csv has. A run that does not is kept in its own file and logged as held, and
latest.csv stays as it was.
Exit 0: the run replaced latest.csv.
Exit 1: the key is missing or nothing came back.
Exit 2: the run was held.
"""
import csv
import json
import os
import shutil
import sys
import urllib.request
from datetime import datetime, timezone
API = "https://api.spider.cloud/crawl"
LATEST = os.path.join("runs", "latest.csv")
LOG = os.path.join("runs", "log.txt")
def count_rows(path):
if not os.path.exists(path):
return 0
with open(path, newline="", encoding="utf-8") as f:
return max(sum(1 for _ in csv.reader(f)) - 1, 0)
def main() -> int:
if len(sys.argv) not in (2, 3) or sys.argv[2:] not in ([], ["--short"]):
print("usage: python3 stop_bad_run.py URL [--short]")
return 1
url = sys.argv[1]
key = os.environ.get("SPIDER_API_KEY")
if not key:
print("set SPIDER_API_KEY first, as in lesson 1")
return 1
os.makedirs("runs", exist_ok=True)
started = datetime.now(timezone.utc)
params = {"url": url, "limit": 20, "request": "http", "return_format": "markdown"}
if "--short" in sys.argv:
params["limit"] = 5
req = urllib.request.Request(API, data=json.dumps(params).encode(), headers={
"Authorization": f"Bearer {key}",
"Content-Type": "application/json",
})
with urllib.request.urlopen(req, timeout=300) as resp:
pages = json.load(resp)
if isinstance(pages, dict):
pages = [pages]
if not pages:
print("nothing came back")
return 1
rows = sorted(((p.get("url") or "", p.get("status"), len((p.get("content") or "").encode()))
for p in pages))
out = os.path.join("runs", started.strftime("quotes-%Y-%m-%dT%H%M%SZ.csv"))
with open(out, "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["url", "status", "bytes"])
writer.writerows(rows)
before = count_rows(LATEST)
whole = all(status == 200 for _, status, _ in rows) and len(rows) >= 0.8 * before
verdict = "ok" if whole else "held"
if whole:
shutil.copyfile(out, LATEST)
with open(LOG, "a", encoding="utf-8") as f:
f.write(f"{started:%Y-%m-%dT%H:%M:%SZ} {url} pages={len(rows)} limit={params['limit']} {verdict}\n")
print(f"this run: {len(rows)} rows in {out}")
print(f"latest.csv before: {before} rows, after: {count_rows(LATEST)} rows")
print(verdict if whole else f"held: {len(rows)} rows is under 80 percent of {before}, latest.csv not replaced")
return 0 if whole else 2
if __name__ == "__main__":
sys.exit(main())As recorded, the params line sends neither a user_agent nor a delay. Before you run your copy, change it so it sends both, with your own bot name and contact address:
params = {"url": url, "limit": 20, "request": "http", "return_format": "markdown",
"user_agent": "examplebot/1.0 (+https://example.com/bot; bot@example.com)", "delay": 1000}A whole run, then a short one
Start in a folder with no runs/latest.csv in it. Run the script on the practice site, then again with --short, and print the exit code each time:
python3 stop_bad_run.py https://quotes.toscrape.com/
echo $?
python3 stop_bad_run.py https://quotes.toscrape.com/ --short
echo $?The pair below ran on 2026-11-20, and the file names show they started seven seconds apart. The full crawl took 2.0 seconds, exited 0 and printed this:
this run: 20 rows in runs/quotes-2026-11-20T223514Z.csv
latest.csv before: 0 rows, after: 20 rows
okThe --short run took 4.0 seconds and exited 2:
this run: 5 rows in runs/quotes-2026-11-20T223521Z.csv
latest.csv before: 20 rows, after: 20 rows
held: 5 rows is under 80 percent of 20, latest.csv not replacedRead the held run
The middle line of the second run is the one to check. latest.csv had 20 rows before the short run and 20 after it. The five rows went to their own dated file, where you can open them and see what the crawl found. A program that reads latest.csv gets the 20 rows from the run before.
The exit code carries the same verdict to whatever started the script. The Bash manual says "a non-zero exit status indicates failure", and it explains why zero is the one code for success: there is "one well-defined way to indicate success and a variety of ways to indicate various failure modes." This script uses two of those ways. Exit 1 means the run never produced rows. Exit 2 means it produced rows and the script would not promote them.
The script also appends a line to runs/log.txt, ending in held for this run. The record of the two runs kept what the terminal printed and each exit code, and it did not keep that file, so this page does not show its lines. After your own short run, tail -n 1 runs/log.txt prints yours.
The recorded script does not stop the crawl partway. It knows the count once the pages are back, so the stop comes after the crawl and before the copy. It also reports every held run as a row shortage. A run with 20 rows and one 404 among them is held too, and the message would still talk about 80 percent.
Put the check into your own script
Copy your edited run_log.py from lesson 11 to stop_bad_run.py. Add import shutil, the LATEST constant and count_rows() from the recorded script, and the argument check on the first line of main().
Lesson 11 ended by having you lower "limit" to 5. Put it back to 20, and add the --short pair under it. If the limit stays at 5, both commands ask for five pages and the short run passes:
params = {"url": url, "limit": 20, "request": "http", "return_format": "markdown",
"user_agent": "examplebot/1.0 (+https://example.com/bot; bot@example.com)", "delay": 1000}
if "--short" in sys.argv:
params["limit"] = 5Add one more constant below LATEST:
KEEP = 0.5Then, inside the try block, replace the line that sets code and the print under it with this:
before = count_rows(LATEST)
if not rows or good != len(rows):
code = 1
print(f"failed: {good} of {len(rows)} pages answered 200")
elif len(rows) < KEEP * before:
code = 2
print(f"held: {len(rows)} rows is under {KEEP:.0%} of {before}, latest.csv not replaced")
else:
shutil.copyfile(out, LATEST)
code = 0
print(f"ok: latest.csv now has {len(rows)} rows")The return code line and the finally block stay as they are, so lesson 11's log line records exit=2 for a held run with no further change.
Half is a looser bar than the recorded 80 percent. The edited code asks two things of a run before it replaces latest.csv: every page answered 200, and the row count is at least half of the last good one. With 20 rows in latest.csv, a run of 10 rows or more that answered 200 on every page replaces the file. A run of 1 to 9 rows, all of them 200, is held and exits 2. A run with a page that did not answer 200 exits 1 with its own message, however many rows it has, and so does a run that brought back no rows at all. Neither touches latest.csv. The recorded cutoff would hold anything under 16. The row check cannot tell you why a count fell, and the recorded runs show only that a limit of 5 saved 5 rows.
Run the same two commands as before. With latest.csv at 20 rows, a --short run that saves 5 rows is under half of 20, so echo $? prints 2. The message reads under 50% of 20, because it prints KEEP itself and follows the constant when you change it.
Try it yourself
Change one value. Set KEEP = 0.2 and run the short crawl again, then count the lines in the file:
python3 stop_bad_run.py https://quotes.toscrape.com/ --short
echo $?
wc -l runs/latest.csvFive rows is not under a fifth of 20, so this time the run passes, and latest.csv shrinks to the short run's rows. The next run will be measured against that smaller count. A file that shrinks a little on every run passes every time, because each run is compared only with the one before it.
Put the file back. Set KEEP to 0.5 again and run the full crawl once:
python3 stop_bad_run.py https://quotes.toscrape.com/
wc -l runs/latest.csvYou are done when the short run's echo $? prints 0 where it printed 2 a minute ago, and each wc -l gives one more line than the row count its run printed, the extra line being the header.
Do this, avoid this
A held run is a reason to look before you crawl again. Open its dated file and see which pages came back before you start the job over, and keep to the request rate from lesson 4 when you do. The row count does not say why it fell, so read the site's robots.txt and its terms again before the next run.
Do this
- Write each run to its own dated file first, and copy it over latest.csv only after the check passes.
- Count the rows in the last good file on every run, so the bar moves with the data and is not a number typed into the script.
- Give a held run an exit code of its own, so the log and the shell can tell it from a run that failed outright.
- Open the held run's dated file and the site itself before you run the job again.
Avoid this
- Writing new rows straight into the file other programs read.
- Rerunning a held job in a loop until it passes.
- Setting the bar so low that a run with a fifth of the rows replaces the good file.
- Deleting the held run's file. It is the only record of what the site returned that time.
Next
The 2026-11-20 pair ended with 20 rows in latest.csv and a 5-row file beside it under its own name. A web scraping job needs that before you leave it alone. You are still the one typing the command, though. The next lesson asks how to have the computer start the job on a schedule.