Python Automation: Scrapers, Batch Files, and Scheduled Jobs
Most office automation starts the same way: a person opens a folder, renames forty files, copies rows out of a spreadsheet, checks a website for a number, and pastes the result somewhere. Python removes the manual step, but a script that only works on the happy path creates a worse problem â you stop looking at the task entirely, so you stop noticing when the input quietly changed. Durable automation is therefore less about the scraping or copying API and more about three unglamorous properties: the script does one job, it reports its own failures, and it can be run twice without corrupting anything.
This lesson builds those properties into a small pipeline: fetch a page politely, parse only the structure you need, transform files in batches, decide how the job should be scheduled, and emit a log line that tells a human whether anything went wrong.
The difference between a snippet and automation
A snippet assumes the world cooperates. It reads a file that exists, parses a field that is present, and runs while you watch the terminal. Automation has to handle the morning after: the file is locked by another process, the website returns a maintenance page, the column was renamed, the disk is nearly full. The cheapest way to deal with all of that is to make every assumption explicit in code, so that a broken assumption raises an exception with context instead of producing a plausible-looking but empty output file.
import csv
import logging
from pathlib import Path
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
)
log = logging.getLogger("nightly-report")
def load_rows(path: Path) -> list[dict]:
if not path.exists():
raise FileNotFoundError(f"expected input at {path}")
if path.stat().st_size == 0:
raise ValueError(f"{path} is empty â export probably failed upstream")
log.info("loaded %s (%d bytes)", path.name, path.stat().st_size)
return list(csv.DictReader(path.open(newline="", encoding="utf-8")))
Notice that neither guard does any real work; both simply convert a silent failure into a named one. When this runs unattended, that name is the difference between a five-minute fix and an afternoon of archaeology.
Fetching pages politely and defensively
requests.get on a URL that happens to work today will still raise on a timeout, a TLS
hiccup, or a 503 that the server sends when you hammer it. Wrap the call, check the status
explicitly, and set a User-Agent that identifies your tool â many sites block the default
Python agent outright, and identifying yourself is both more reliable and more polite.
import requests
HEADERS = {"User-Agent": "internal-report-bot/1.0 (+mailto [email protected])"}
def fetch(url: str, *, retries: int = 3, timeout: float = 10.0) -> str:
last = None
for attempt in range(1, retries + 1):
try:
resp = requests.get(url, headers=HEADERS, timeout=timeout)
resp.raise_for_status()
return resp.text
except requests.RequestException as exc:
last = exc
log.warning("attempt %d/%d failed for %s: %s", attempt, retries, url, exc)
raise RuntimeError(f"giving up on {url}") from last
A short retry loop with backoff absorbs transient errors; a hard failure after the retries
are exhausted tells you the problem is structural. Also check Content-Type before you
parse â a login redirect returning HTML where you expected JSON is one of the most common
silent corruption sources in web automation.
Parsing only the structure you depend on
BeautifulSoup will happily build a DOM of the entire page, but your script should declare the smallest possible contract with that page: one selector for the headline, one for the table, one for the timestamp. If you select the twentieth ancestor of a div, the first redesign breaks you; if you select a class name the site actually uses for layout, the same redesign breaks you.
from bs4 import BeautifulSoup
def extract_prices(html: str) -> list[dict]:
soup = BeautifulSoup(html, "html.parser")
rows = []
for tr in soup.select("table.prices tbody tr"):
cells = tr.find_all("td")
if len(cells) != 3:
log.warning("skipping malformed row with %d cells", len(cells))
continue
rows.append({
"product": cells[0].get_text(strip=True),
"price": cells[1].get_text(strip=True),
"updated": cells[2].get_text(strip=True),
})
if not rows:
raise ValueError("no rows matched â page layout may have changed")
return rows
Returning an empty list without complaint is the classic scraper bug: the job reports success, and a dashboard quietly shows last week's numbers forever. Raise instead.
Give the parser a thin wrapper rather than scattering BeautifulSoup calls through the script. When the site redesigns, you then repair one function, and every caller inherits the fix. Keep a saved copy of a real page next to the code and add a test that extracts from the fixture: that test will tell you the layout changed before your stakeholders do, and it runs in milliseconds without touching the network.
Batch file work that is safe to rerun
For directory work, pathlib gives you a consistent vocabulary â glob, mkdir,
with_name, suffix â and shutil covers copy, move, and tree deletion. The rule that
prevents most accidents is idempotency: running the same job twice should leave the same
result, which usually means writing into a temporary name and renaming atomically at the
end.
| Task | Prefer | Avoid | Why |
|---|---|---|---|
| Build a path | Path("out") / name | "out/" + name | Works across operating systems |
| Create a folder | mkdir(parents=True, exist_ok=True) | os.system("mkdir ...") | No shell, no crash if it exists |
| Find files | sorted(root.glob("**/*.csv")) | os.listdir plus string filters | Recursive, typed, chainable |
| Move results | shutil.move(tmp, final) | write directly to final | Readers never see a half file |
| Delete a tree | shutil.rmtree(temp) | os.system("rm -rf") | Raises instead of silently ignoring |
import csv
import shutil
from pathlib import Path
def consolidate(src_dir: Path, dest: Path) -> int:
files = sorted(src_dir.glob("*.csv"))
if not files:
raise FileNotFoundError(f"nothing to consolidate in {src_dir}")
tmp = dest.with_suffix(".partial")
total = 0
with tmp.open("w", newline="", encoding="utf-8") as out:
writer = None
for f in files:
with f.open(newline="", encoding="utf-8") as fh:
reader = csv.DictReader(fh)
if writer is None:
writer = csv.DictWriter(out, fieldnames=reader.fieldnames)
writer.writeheader()
for row in reader:
writer.writerow(row)
total += 1
shutil.move(str(tmp), str(dest))
log.info("consolidated %d rows from %d files into %s", total, len(files), dest.name)
return total
Because the output is written to report.partial and only renamed at the end, a crash
mid-run leaves the previous good file untouched â you can simply rerun.
Choosing how the job gets scheduled
The scheduling mechanism you pick determines your failure modes, so choose it deliberately rather than defaulting to whatever example you copied.
| Option | Best for | Weakness |
|---|---|---|
cron / Task Scheduler | Fixed-interval jobs on one machine | No built-in logging, overlap, or retry |
The schedule library | Long-running processes already in Python | Dies with the process |
| systemd timer / launchd | Supervised services with restart policy | Platform specific |
| Airflow or Prefect | Dependencies between many jobs | Operational overhead |
| CI workflow (for example GitHub Actions) | Data jobs tied to code changes | Minutes-long cold start |
Whichever you choose, lock the job so that two instances never run at once â a monthly export that occasionally overlaps itself will double-send reports before anyone notices.
Making failure visible to a human
Unattended jobs need a destination for their bad news. At minimum, write structured log lines with a timestamp and a stable message; better, route errors to a channel a person watches, and let silence itself be a signal by emitting a heartbeat on success so that missing output is detectable.
import smtplib
from email.message import EmailMessage
def notify(subject: str, body: str, ok: bool = True) -> None:
msg = EmailMessage()
msg["From"] = "[email protected]"
msg["To"] = "[email protected]"
msg["Subject"] = ("[ok] " if ok else "[failed] ") + subject
msg.set_content(body)
with smtplib.SMTP("localhost") as smtp:
smtp.send_message(msg)
try:
rows = consolidate(Path("inbox"), Path("reports/consolidated.csv"))
notify("nightly consolidation", f"{rows} rows written")
except Exception as exc:
log.exception("nightly consolidation failed")
notify("nightly consolidation", str(exc), ok=False)
raise
Raising after notifying matters: it lets the scheduler record a non-zero exit code, so monitoring sees the failure even if the mail server also had a bad night.
Knowing when a script has outgrown itself
You have crossed the line from automation into software when the script accumulates
configuration, credentials, retries, and a queue of inputs. At that point the honest move
is to promote it â a package with a pyproject.toml, secrets read from the environment,
tests around the parsing logic, and a container so the next system upgrade does not
silently change a regex's behaviour. Until then, keep the script small, keep its
assumptions written down, and prefer raising an exception over printing a warning nobody
will read.
Common Mistakes
Treating an empty scrape result as success and publishing stale numbers
Fix: Raise when zero rows match, so the job fails loudly instead of quietly repeating yesterday
Writing output directly over the file consumers read
Fix: Write to a temporary path, then rename â readers only ever see a complete file
Scraping with the default User-Agent and no timeout
Fix: Identify your bot, set a timeout, and retry with backoff before giving up
Hard-coding paths, credentials, and thresholds inside the script
Fix: Read them from environment variables or a config file so changes do not require a code edit
Letting two scheduled runs of the same job overlap
Fix: Take a lock file or rely on the scheduler's non-overlap guarantee
Best Practices
- Log with timestamps and stable message text so failures can be grepped a month later
- Make every job idempotent: rerunning it after a crash must produce the correct final state
- Select the smallest HTML structure you need, and raise the moment that structure disappears
- Wrap external calls â HTTP, SMTP, filesystem â with explicit retries and contextual errors
- Ship a heartbeat on success so that silence is itself a detectable alarm
Key Takeaways
- Automation quality is measured by how it behaves when the input is wrong, not when it is right
- Guard every assumption (file exists, page has rows, type is what you expect) with a named exception
- pathlib plus shutil covers most batch work, and atomic rename protects readers from partial output
- Pick a scheduler for its failure handling: locking, logging, and retries matter more than convenience
- Failures must reach a human â log them, mail them, and still exit non-zero