Sub topic 16
Scaling the Workflow with Scripts and Tools
This chapter assumes you have already worked through the manual versions of both tactics. You should know how to read an HTTP status code, how a mention is verified as unlinked, and how outreach is tracked. Scaling adds speed, but it does not replace the judgment you built in those steps. Here you will learn which steps are safe to automate, how to chain the two scripts from earlier chapters into one pipeline, and where automation breaks.
What to automate and what to keep manual
Some steps are mechanical and some need judgment. Automate the mechanical ones.
| Step | Automate? | Reason |
|---|---|---|
| Fetching pages and extracting links | Yes | Repetitive, with clear rules |
| Checking HTTP status of each link | Yes | A machine does it faster and more consistently |
| Detecting whether a mention has a link | Yes | A deterministic HTML check |
| Deduplicating prospects and logging results | Yes | Prevents contacting the same site twice |
| Judging relevance and replacement fit | No | Needs reading the page and understanding intent |
| Writing the outreach message | Partly | Fill in a template, but a person reviews each one |
| Sending the message | No | Bulk sending reads as spam and risks your domain |
A useful rule: let scripts produce a shortlist, and let a person decide who gets contacted.
The pipeline
Both tactics follow the same shape. Discover candidate pages, test each one, store the results, then review them by hand.
Reusing the two core checks
The broken link script and the mention check from earlier chapters are the two engines. Run them over a list of URLs instead of one page at a time.
The script below imports both functions and writes one CSV. It assumes you saved the earlier functions in a module named linkchecks.py, with find_broken_links and is_unlinked_mention defined as before. It reads candidate URLs from candidates.txt, one per line.
import csv
import time
import requests
from linkchecks import find_broken_links, is_unlinked_mention
HEADERS = {"User-Agent": "link-audit/1.0"}
DELAY_SECONDS = 2
def read_urls(path):
with open(path, encoding="utf-8") as f:
return [line.strip() for line in f if line.strip()]
def run(path, brand, domain, out_path):
rows = []
for url in read_urls(path):
try:
broken = find_broken_links(url)
html = requests.get(url, headers=HEADERS, timeout=10).text
mention = is_unlinked_mention(html, brand, domain)
error = ""
except requests.RequestException as exc:
broken, mention, error = [], False, str(exc)
rows.append({
"page": url,
"broken_count": len(broken),
"broken_urls": " | ".join(u for u, _ in broken),
"unlinked_mention": mention,
"error": error,
})
time.sleep(DELAY_SECONDS)
with open(out_path, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(
f,
fieldnames=["page", "broken_count", "broken_urls", "unlinked_mention", "error"],
)
writer.writeheader()
writer.writerows(rows)
if __name__ == "__main__":
run("candidates.txt", "Acme Analytics", "acme-analytics.com", "audit.csv")The time.sleep call is deliberate. It keeps your crawl polite and lowers the chance that a site blocks you.
Making the checks faster without being rude
The loop above is slow because it waits on the network. Two changes help: run requests in parallel, and limit how hard you hit any single host.
Parallelism is safe when the URLs belong to different sites. It is not safe when many URLs share one host, because you would send many requests at once to the same server. Group URLs by host and keep one worker per host.
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import urlparse
def group_by_host(urls):
groups = defaultdict(list)
for url in urls:
groups[urlparse(url).netloc].append(url)
return groups
def process_host(urls):
results = []
for url in urls:
results.append((url, len(url))) # replace with a real check
return results
def run_parallel(urls, workers=8):
groups = group_by_host(urls)
with ThreadPoolExecutor(max_workers=workers) as pool:
batches = pool.map(process_host, groups.values())
return [item for batch in batches for item in batch]
if __name__ == "__main__":
sample = [
"https://example.com/a",
"https://example.com/b",
"https://example.org/c",
]
print(run_parallel(sample))Each host gets one worker that processes its pages in order. Replace the placeholder inside process_host with a call to your real check and add a short sleep between requests there.
Rules for responsible crawling
- Check
robots.txtbefore crawling a site. Python'surllib.robotparserreads it for you. - Send an honest
User-Agentwith a way to contact you, not a browser impersonation. - Back off when you see 429 (too many requests) or repeated 5xx responses. Waiting longer is the correct response, not retrying faster.
- Set a timeout on every request. Without one, a single hung server can stall the whole run.
- Cache results so you never fetch the same URL twice in a session.
Tools versus your own scripts
Commercial SEO platforms and browser-based crawlers cover much of this work. Scripts give you control, and tools give you scale and data you cannot collect yourself.
| Need | Scripts | Tools |
|---|---|---|
| Crawl one page or a short list | Quick to write | Often more than you need |
| Crawl a whole site for broken outbound links | Possible, takes effort | Site crawlers do this out of the box |
| Find pages that link to a dead competitor URL | Not feasible alone | Backlink index tools hold this data |
| Ongoing brand mention alerts | Fragile to build | Alert services and mention monitors handle it |
| Custom verification rules | Easy to tailor | Limited to what the tool exposes |
| Cost | Your time | Subscription fees |
A common split is to use tools for discovery, where their data is unique, and scripts for verification, where your own rules matter. Export a list of pages from a backlink or mention tool as CSV, then feed that list to your verification script.
Keeping state so you do not repeat yourself
Automation makes it easy to contact the same person twice. Keep a small record of every prospect and its stage. A CSV works for a start. Track at least the page URL, the contact, the date of each message, and the outcome.
import csv
from datetime import date
from pathlib import Path
LOG = Path("outreach_log.csv")
FIELDS = ["page", "contact", "stage", "last_contacted"]
def load_log():
if not LOG.exists():
return {}
with LOG.open(newline="", encoding="utf-8") as f:
return {row["page"]: row for row in csv.DictReader(f)}
def save_log(log):
with LOG.open("w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=FIELDS)
writer.writeheader()
writer.writerows(log.values())
def already_contacted(log, page):
return page in log
def record(log, page, contact, stage):
log[page] = {
"page": page,
"contact": contact,
"stage": stage,
"last_contacted": date.today().isoformat(),
}
if __name__ == "__main__":
log = load_log()
page = "https://example.org/resources"
if not already_contacted(log, page):
record(log, page, "[email protected]", "first_email_sent")
save_log(log)
print(len(log), "prospects logged")Before any batch of outreach, filter your shortlist against this log. This also feeds the success rate calculation from the tracking chapter: links won divided by messages sent.
Failure modes at scale
- False positives in broken link detection. Soft 404s return status 200 for a page that says "not found". The status check cannot see them, so sample results by hand.
- False negatives in mention detection. A brand written as "AcmeAnalytics" or an abbreviation will not match your pattern. Add known variants to the list you search for.
- Stale data. A page you checked last month may have been fixed. Re-check a link just before you email about it.
- JavaScript-rendered pages.
requestsfetches the raw HTML. Links added by scripts in the browser will be missing. For those pages, use a headless browser or review by hand. - Template fatigue. If every email looks the same, replies drop. Insert a real detail from the page into each message.
A weekly routine
- Export new candidate pages from your discovery tools and append them to
candidates.txt. - Run the audit script and open
audit.csv. - Sort by
broken_countand theunlinked_mentionflag, then remove pages already in the outreach log. - Review the top results manually for relevance and confirm each broken link in a browser.
- Write and send personalized messages, then record each one in the log.
- Re-check earlier prospects for replies and new links, and send one follow-up where appropriate.
Exercise
Your audit script reports that a page has 12 broken links, and 9 of them have status 403. What should you do before including this page in outreach, and why?
Show answer
Treat the 403 results as unknown rather than broken. A 403 often means the server is blocking automated requests, not that the page is gone. Open those links in a browser and confirm which ones really fail. Only the confirmed dead links count toward the page's prospect score.
Exercise
You run 8 parallel workers over 400 URLs, and 150 of them are on the same host. Why is that a problem, and how do you fix it?
Show answer
Parallel workers would send many simultaneous requests to one server, which can overload it or get your crawler blocked. Group URLs by host and assign one worker per host, with a delay between requests to that host. Different hosts can still run in parallel.