Link extraction turns webpage anchors into structured records containing destination, anchor text, location, and relationship attributes. Useful analysis requires URL resolution and normalization, not just collecting raw href strings.
Inspect and export a public page with ToolTrace's free Link Extractor.
Fetch the correct page version
Links point at URLs, but they only mean something relative to the page they appeared on. Record both the URL you requested and the final URL after redirects, because that final URL is the base for every relative href on the page.
Send a real User-Agent, follow redirects, cap the response size, and set an explicit timeout. The requests library in Python does all of this with two or three lines, but you still have to decide what counts as a successful fetch.
A 200 status is not enough. Check that the Content-Type is HTML, that the body is above a sensible minimum size, and that it contains the elements you expect. A paywall, a consent gate, or a bot challenge will all return 200 with an empty-looking document.
Decide whether to render JavaScript. Many publishers now inject part of their link graph after load through client-side navigation and lazy-loaded sections. If a static fetch returns ten links and the browser shows a hundred, you need a headless renderer or an API that handles it. For most SEO use cases, start with static HTML and escalate only when you can prove links are missing.
Save the final URL alongside every link record. Teams that skip this end up with resolved URLs that point at the wrong directory because somebody forgot that /blog redirected to /blog/.
Collect anchors and useful context
An anchor tag is more than its href. The useful record captures visible text, relationship attributes, the surrounding section, and any image alt text when the anchor wraps an image instead of words.
Visible text should be collapsed whitespace, not raw textContent. The CSS selector a[href] is a safer starting point than a, because unlinked anchors still exist in older markup and you do not want them polluting the dataset.
Capture rel as a list rather than a string. A single anchor can carry rel="nofollow sponsored ugc", and collapsing that into one flag erases a distinction that search engines actually use. Hold on to title, aria-label, and download too. They tell you what the publisher thinks the link is.
Handle non-navigational schemes separately. mailto:, tel:, javascript:, and data: are all valid href values but none of them belong in a crawlable link inventory. Bucket them, do not drop them silently, because inventory counts should still add up.
Note where each anchor lives. A link in the main article body carries a different weight than one in a sidebar, footer, or related-posts rail. Capture at least a container selector or section ID. The free SEO Page Inspector labels these zones automatically.
Resolve and normalize URLs
Normalization is where most homegrown extractors drift. Two URLs that look different can mean the same resource, and two that look identical can resolve to different pages.
Start with urljoin in Python or the URL constructor in JavaScript. Both follow the WHATWG URL Standard closely enough that the result matches what a browser would do. Rolling your own parser is a losing fight.
Lowercase the scheme and host, but not the path. HTTPS and https are the same scheme; /About and /about are not the same path on most servers. Strip default ports (:80 for HTTP, :443 for HTTPS) so https://example.com:443/ and https://example.com/ collapse into one record.
Query parameters are the hard part. Sorting them makes ?b=2&a=1 equal to ?a=1&b=2, which is almost always what you want for a link inventory. But do not strip them blindly. UTM parameters, product variants, and pagination tokens all look like tracking until you check.
Decide a fragment policy and stick to it. For an SEO link audit, treat /page and /page#section as the same destination. For an in-page navigation review, keep the fragment because it is the whole point.
Handle internationalized domains with Punycode. A link to bücher.example and xn--bcher-kva.example is the same site, and your normalizer should know that before the dedupe step runs.
Classify internal, external, resource, and tracking links
Classification turns a flat list into something you can filter and act on. Four buckets cover almost every case: internal, external, resource, and non-navigational.
Internal links match the canonical host or a declared subdomain policy. If blog.example.com and example.com are the same brand, record them as internal and tag the subdomain. If help.example.com is a hosted help desk you do not control, that is external even though the brand matches.
Resource links point at files that are not pages: PDFs, CSVs, images, zips. Detect them by extension and by Content-Disposition when you have fetched them. They matter for crawl budget and for accessibility review, but they do not belong in your internal-link graph.
Tracking and redirector links deserve a bucket of their own. Known click trackers, affiliate shims, and short links hide the real destination behind one or two hops. For an audit, follow those hops and record the resolved URL as the destination. For a privacy review, record both.
Capture rel values individually rather than as a boolean. The difference between nofollow, sponsored, and ugc is semantic. A link marked sponsored is a disclosure of a paid relationship; one marked ugc is a disclosure that a user wrote it. Collapsing both into "nofollow" loses an auditable signal.
Flag utility links such as login, cart, search, and language switchers. They clutter inventories and are rarely useful for SEO decisions, but they are useful for QA checks on site-wide navigation.
Extract links in Python with BeautifulSoup and lxml
Two Python approaches cover most link extraction work. Pick based on how much HTML you are processing and how deeply you need to inspect the DOM.
BeautifulSoup with the lxml parser is the readable default. Good for one URL at a time, easy to debug, and the API matches how most tutorials describe the DOM. Install beautifulsoup4==4.12.3, lxml==5.2.2, and requests==2.32.3.
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlparse
url = "https://example.com/"
response = requests.get(url, timeout=20, headers={"User-Agent": "ToolTrace/1.0"})
response.raise_for_status()
final_url = response.url
soup = BeautifulSoup(response.text, "lxml")
base_tag = soup.find("base", href=True)
base = urljoin(final_url, base_tag["href"]) if base_tag else final_url
links = []
for a in soup.select("a[href]"):
absolute = urljoin(base, a["href"].strip())
parsed = urlparse(absolute)
if parsed.scheme not in ("http", "https"):
continue
links.append({
"url": absolute,
"host": parsed.netloc.lower(),
"text": a.get_text(" ", strip=True),
"rel": a.get("rel", []),
"title": a.get("title"),
})Three details matter here. The base element overrides the document URL for relative resolution. The strip() catches whitespace in sloppy templates. The scheme filter removes mailto:, tel:, and javascript: without a separate branch.
Pure lxml is faster when you are processing thousands of pages. The API is less friendly, but the parser is the same C library BeautifulSoup wraps, and skipping the Python layer is measurable at scale. Use lxml.html directly.
import requests
import lxml.html
from urllib.parse import urlparse
response = requests.get("https://example.com/", timeout=20)
tree = lxml.html.fromstring(response.content)
tree.make_links_absolute(response.url, resolve_base_href=True)
links = []
for a in tree.xpath("//a[@href]"):
href = a.get("href")
parsed = urlparse(href)
if parsed.scheme not in ("http", "https"):
continue
links.append({
"url": href,
"host": parsed.netloc.lower(),
"text": (a.text_content() or "").strip(),
"rel": (a.get("rel") or "").split(),
})make_links_absolute handles the base element and relative URLs in one call, which is the main reason to reach for lxml directly on larger jobs.
Neither snippet renders JavaScript. On a client-rendered page both return whatever anchors the server sent, which is sometimes just a shell. For those pages, use a headless browser or hand the URL to the Link Extraction API, which renders before extracting and returns resolved, classified records.
In the browser console, a one-liner is enough for a page you are already looking at:
[...document.querySelectorAll("a[href]")].map(a => ({
url: a.href,
text: a.textContent.trim(),
rel: a.rel,
}));The a.href property is already absolute and already respects any base element, which saves the manual resolution step. Without code at all, the free Link Extractor does the same work including rel attributes and classification, and renders the page first where that is needed.
Deduplicate without losing anchor context
A page that lists the same product in a grid, a sidebar, and a footer will produce three records that resolve to the same URL. Collapsing them hides a real signal: the destination was linked three times with three different anchor texts.
Keep two views. A destination-level inventory counts each unique resolved URL once, with occurrence count, dominant anchor text, and all unique anchor variants. A placement-level log keeps every record, with location metadata, for anchor and context analysis.
Flag anchor-text patterns rather than deduplicating them away. Empty text, "click here", "read more", and raw URLs as link text all point at the same accessibility and SEO problem. Count them, surface them, and let the auditor decide what to rewrite.
Respect robots.txt, rate limits, and nofollow
Link extraction looks harmless because you are only reading a page, but at scale it is still crawling. Be a decent client.
Check robots.txt before fetching. Python ships urllib.robotparser, and most mature scrapers wrap it. Respect Disallow rules for the user agent you present. If you present a generic User-Agent, you are agreeing to the rules for *.
Rate limit. One concurrent request per host is a safe default; two or three is fine for larger sites but should back off on 429 or 503. Random jitter between requests avoids a lockstep pattern that looks like an attack.
Honor Retry-After. If a server returns it, wait that long. If a server returns 429 without a header, use exponential backoff and give up after a few tries rather than hammering until a human notices.
Attribute requests clearly. A User-Agent that identifies the tool and includes a contact URL makes it easy for a site owner to reach you if something goes wrong, which is better than being quietly blocked.
Treat nofollow, sponsored, and ugc as data, not instructions. These attributes describe the publisher's trust in the destination; they do not forbid you from recording the link. But for a crawler that walks the graph, nofollow is a reasonable stop signal unless you have a specific reason to follow it.
Check terms of service before scraping anything beyond a single public page. Public does not mean unrestricted, and copyright and database rights still apply to extracted datasets. For links on your own site, this is a non-issue. For links on sites you do not own, read the ToS and respect it. The web scraping API quickstart covers the production patterns in more depth.
Audit and export the link dataset
Extraction is the input, not the deliverable. The audit is where the dataset earns its weight.
Resolve every destination you plan to act on. A link that returns 200 today may redirect to a redirect to a 404 next quarter, and a chain of three hops is almost always a mistake somebody never cleaned up. Record the full redirect chain and the final status.
Look for weak anchors on important internal destinations. If your pricing page is linked twenty times with "here" and twice with "pricing", that is an easy fix. The Link Extractor surfaces anchor variants side by side so these show up without a spreadsheet pivot.
Compare internal-link counts against your site structure. A page you consider important that receives one or two internal links is probably losing authority to pages that receive dozens. Pair this with the on-page SEO audit for a per-URL view.
Export in two formats. CSV is friendly for review in a spreadsheet and for sharing with non-technical stakeholders. JSON preserves nested fields like rel arrays and placement metadata without flattening. Include source URL, final destination, host, class, anchor variants, rel values, occurrence count, extraction time, and final status so a reader can reproduce the record.
Treat extraction as a snapshot. Re-run on a cadence that matches how often the page changes, and diff the dataset to surface new, removed, or redirected links. For richer content work on the same page, continue with the article text extraction workflow.
Classify links for the actual analysis job
Define internal and external using the effective site boundary, not a simple string prefix. Decide how subdomains, alternate ports, international domains, CDN hosts, fragments, query parameters, and redirected destinations should be treated. Preserve the original href beside the resolved URL so normalization remains auditable.
- Group repeated destinations and count their occurrences.
- Keep distinct anchor text even when URLs match.
- Record
relvalues such asnofollow,sponsored, andugc. - Separate navigation, editorial, footer, image, and action links when location is available.
For SEO work, compare the inventory with the page purpose and identify missing contextual routes, generic anchors, broken destinations, and isolated pages.
Validate and monitor link inventories
Manually inspect samples from internal, external, fragment, redirect, and excluded groups. Check that URL resolution uses the final document base and that unsafe schemes never enter a crawler queue. If JavaScript creates essential navigation, compare static and rendered results before escalating every page to a browser.
Track total links, unique destinations, broken links, redirect chains, generic anchors, nofollow distribution, and newly introduced external domains. Use the Link Extraction API for repeatable inventories and connect findings to the broader on-page SEO audit workflow.
Common failure patterns and how to diagnose them
Start with the earliest failing layer. If a request does not return the expected page, inspect DNS, redirects, HTTP status, content type, firewall behavior, and access controls before changing extraction or metadata rules. If the correct document arrives but the result is empty, compare initial HTML with the rendered page and determine whether JavaScript supplies the missing information.
When only some fields are wrong, inspect the page source and identify which signal produced each value. A stale canonical, duplicated title, malformed JSON-LD block, relative URL, or CMS fallback should be corrected at its source. Avoid adding a special case for one URL when the same template defect affects a wider section of the site.
Finally, distinguish a deterministic failure from a recommendation. Invalid JSON, an unreachable URL, or a conflicting index directive can be proven. Content usefulness, ideal wording, and business priority still require human judgment. A professional report should show the evidence, explain the consequence, and avoid presenting a heuristic as a universal rule.
Production quality checklist
Validate the exact production URL, not only a CMS preview, local fixture, or isolated code sample. Confirm the requested URL, final URL, HTTP status, content type, and visible result agree with the page you intended to process. Test at least one normal case, one sparse page, one redirected URL, and one expected failure so the interface communicates limitations clearly.
- Keep source URLs and observation times with exported results.
- Use descriptive labels, headings, and error messages.
- Specify image dimensions and keep media files lightweight.
- Test keyboard access and narrow mobile layouts.
- Separate automatic checks from recommendations requiring judgment.
- Respect access controls, publisher policies, privacy, and applicable law.
After deployment, rerun the workflow against representative URLs and monitor for changes in output size, missing fields, status codes, response time, and template behavior. Keep a known-good result for comparison. When a check fails, fix the source template or data pipeline rather than hiding the warning in the interface.
Frequently asked questions
Are JavaScript-generated links included?
Only when the page is rendered in a real browser before extraction. A plain requests fetch sees only what the server sent, which on client-rendered sites can be a near-empty shell. Use a headless browser or an API that renders first when the links you need appear after load.
Should duplicate links be removed?
Keep two views instead of picking one. A destination-level inventory shows each unique resolved URL once with its occurrence count and anchor variants. A placement-level log keeps every record for anchor-text and location analysis.
Are external links bad for SEO?
No. Relevant, trustworthy external links support readers and claims, and search engines treat them as a quality signal when the context fits. Rel attributes should reflect the actual relationship: sponsored for paid, ugc for user-generated, nofollow for links you cannot vouch for.
How many links should a page have?
There is no fixed limit. Google retired the old 100-link guideline years ago. Judge by whether the links help the reader finish the task. A navigation-heavy template that pushes 300 links before the main content starts is usually a different kind of problem.
What is the difference between a link extractor and a crawler?
A link extractor pulls links from a single page in one pass. A crawler follows those links to new pages, respecting robots.txt and depth or budget limits, and repeats the process. Most audit workflows start with extraction and only escalate to crawling when the site-wide graph matters.
Is it legal to extract links from a website I do not own?
Reading a public page is generally allowed, but copying, storing, or redistributing extracted data can trigger terms-of-service, copyright, and database-rights issues depending on jurisdiction. Read the site's terms and robots policy, limit the data you keep to what you need, and consult a lawyer for anything commercial.
What is the fastest way to extract links without writing code?
Paste the URL into the free Link Extractor. It fetches the page, renders JavaScript when needed, resolves relative URLs, captures rel values, classifies internal and external links, and exports a deduplicated list. Useful when the goal is the dataset, not the script.