Sub topic 5
Finding Broken Outbound Links on Relevant Pages
This chapter assumes you know what a backlink and anchor text are, can read basic HTML anchor tags, and recognize status codes such as 200, 301 and 404. You will learn how to pick pages worth checking, how to test their outbound links, and how to avoid false positives before you contact anyone.
The goal: broken links on pages that matter
A broken outbound link is a link on someone else's page that points to a destination that no longer works. Finding one is easy. Finding one that can lead to a link for you is harder, because the page also has to be relevant to your content, be maintained by a person who can edit it, and be worth the link.
The work has two stages:
- Build a list of relevant pages that are likely to hold outbound links.
- Check every outbound link on those pages and keep the ones that are truly broken.
Do stage one carefully. Checking links is cheap with a script, but a list of irrelevant pages gives you broken links that you cannot use.
Finding candidate pages
Resource pages, "best of" lists, link roundups, university course pages, and long guides tend to hold many outbound links. They also tend to age, so links on them break over time.
Search operators help you locate them. The query below looks for resource pages on web analytics that have "links" in the URL.
intitle:resources "web analytics" inurl:linksOther ways to find candidates:
- Search for your main keyword with words such as "resources", "useful links", "further reading", or "recommended tools".
- Look at the pages that already link to your competitors. These pages have shown they link to your topic.
- Use an SEO tool to list the pages that link to a known dead page in your niche. Many tools can show backlinks to a URL that now returns 404.
- Run a crawler or a browser extension on a single promising page for a quick check.
Judge each candidate before you test it. Ask whether the topic matches yours, whether the page is still maintained (look at dates and recent edits), and whether the site is one you would be glad to be mentioned on. Chapter content on prospect qualification covers this in more detail. For now, a quick filter is enough.
Testing links with a script
A script lets you check hundreds of links in a few minutes. The function below fetches a page, resolves each link to a full URL, and reports links that fail to connect or return 404, 410 or a server error.
import requests
from urllib.parse import urljoin, urlparse
from bs4 import BeautifulSoup
HEADERS = {"User-Agent": "link-audit/1.0"}
def find_broken_links(page_url, timeout=10):
html = requests.get(page_url, headers=HEADERS, timeout=timeout).text
soup = BeautifulSoup(html, "html.parser")
broken = []
seen = set()
for a in soup.find_all("a", href=True):
url = urljoin(page_url, a["href"])
if urlparse(url).scheme not in ("http", "https") or url in seen:
continue
seen.add(url)
try:
resp = requests.head(url, headers=HEADERS, allow_redirects=True, timeout=timeout)
if resp.status_code in (403, 405, 501):
resp = requests.get(url, headers=HEADERS, stream=True, timeout=timeout)
resp.close()
status = resp.status_code
except requests.RequestException:
status = None
if status is None or status in (404, 410) or status >= 500:
broken.append((url, status))
return broken
if __name__ == "__main__":
for url, status in find_broken_links("https://example.com/resources"):
print(status, url)How the script works
urljointurns relative links such as/guideinto full URLs, using the page address as the base.- The scheme check skips
mailto:,tel:andjavascript:links, which are not web pages. Theseenset stops the same URL being tested twice. requests.headasks only for headers, so it is faster and lighter on the target server than downloading the whole page.- Some servers reject HEAD requests with 403, 405 or 501. For those, the script falls back to a GET request with
stream=True, which reads the headers without downloading the body, and then closes the connection. allow_redirects=Truefollows redirects, so the status you see belongs to the final destination.- A network failure raises
RequestException. The script records that asNone.
What the script does not catch
The script is a first filter. It has gaps you need to know about.
| Situation | What the script sees | What is really happening |
|---|---|---|
| Soft 404 | 200 | The server shows a "not found" message but sends a success code. |
| Redirect to the home page | 200 | The old URL redirects to an unrelated page, so the content is gone. |
| Domain expired and parked | 200 | A parking page answers for the domain. |
| Bot blocking | 403 or 429 | The server refuses automated requests but works in a browser. |
| Temporary outage | 500 or timeout | The site may be back in an hour. |
| Links added by JavaScript | Not found | `BeautifulSoup` reads only the raw HTML, not links created in the browser. |
Handling soft 404s and redirects
A soft 404 is a page that tells the visitor the content is missing but answers with status 200. A simple check can flag likely soft 404s by looking at the final URL and the page text.
import requests
HEADERS = {"User-Agent": "link-audit/1.0"}
PHRASES = ("page not found", "no longer available", "does not exist")
def looks_like_soft_404(url, timeout=10):
resp = requests.get(url, headers=HEADERS, allow_redirects=True, timeout=timeout)
if resp.status_code != 200:
return False
text = resp.text.lower()
short = len(text) < 2000
has_phrase = any(p in text for p in PHRASES)
went_to_root = resp.url.rstrip("/").count("/") <= 2 and url.rstrip("/").count("/") > 2
return has_phrase or (short and went_to_root)
print(looks_like_soft_404("https://example.com/old-guide"))The function checks three signs: common error phrases, a very short page, and a deep URL that ended on a top-level address after redirects. These are heuristics. Treat a True result as a reason to look at the page, not as proof.
Verify before you act
Every link that your script flags should pass three checks before it goes on your list.
- Open it in a browser. This shows what a visitor sees, including blocks that affect scripts only.
- Recheck after a day or two. This removes temporary outages. A link that fails twice on different days is a better prospect than one that failed once.
- Check the link's role on the page. A dead link inside a paragraph about your topic is a strong opportunity. A dead link in a footer or a sidebar widget is weak, because the owner is less likely to edit it.
Also note how many times the dead destination is linked from the page. If one dead resource appears many times on the same site, a single fix can replace several links, so it is worth more.
Saving results for later chapters
Write the verified results to a CSV file, because the next steps (finding what the dead page said, choosing a replacement, outreach, and tracking) all need the same fields.
import csv
from datetime import date
def save_prospects(rows, path="broken_links.csv"):
with open(path, "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["source_page", "broken_url", "status", "checked_on"])
for source_page, broken_url, status in rows:
writer.writerow([source_page, broken_url, status or "no response", date.today().isoformat()])
save_prospects([("https://example.com/resources", "https://old-site.example/guide", 404)])Keep the date. A link that was dead last month may have been fixed since, so you need to know how fresh each row is.
Politeness and limits
Your script sends requests to servers owned by other people. Keep it considerate:
- Identify yourself with a clear
User-Agent, as the examples do. - Limit your request rate. Add a short pause between requests, such as
time.sleep(1), and avoid hitting one host with many parallel requests. - Check the site's
robots.txtif you plan to crawl many pages on it. - Run the script on a candidate list you chose, not on whole sites without reason.
Common errors
- Counting every non-200 as broken. Redirects (301, 302) usually lead somewhere that works. Follow them and judge the final response.
- Ignoring relative links. Without
urljoin, relative links produce invalid URLs and false failures. - Testing links to your own competitors' dead pages only. The dead page matters less than the page that links to it. A relevant, maintained linking page is what makes the opportunity.
- Skipping the manual check. A script cannot see everything a visitor can.
- Using too short a timeout. A timeout of one or two seconds marks slow but working sites as dead. Ten seconds is a reasonable default.
Exercise
A script reports that a link on a resources page returns 403 on both the HEAD and the GET request. You can open the same link in your browser without trouble. Is it a broken link prospect, and what should you do?
Show answer
No. The server is blocking automated requests, not missing the page. Treat a 403 as "unknown" until you check it in a browser. Since it loads normally, discard it and do not email the site owner about it.
Exercise
The script marks a link as fine because it returns 200, but when you open it you see a page saying "This page has moved or no longer exists". What is this called, and how could you catch it automatically?
Show answer
It is a soft 404. You can catch many of them by searching the response text for error phrases, checking whether the page is very short, and checking whether a deep URL redirected to the site's home page. These are heuristics, so confirm any hit by hand.