Main-content extraction identifies the part of a webpage a reader came to consume, preserves its useful structure, and removes the surrounding interface. A reliable result also retains provenance and enough metadata to verify the source.
This workflow supports research, migration, search, summarization, and retrieval-augmented generation. Inspect a real public URL with ToolTrace's free Article Text Extractor while following the steps.
Define the extraction output
Start with the consumer. A RAG pipeline wants paragraphs it can embed. A migration script wants headings, images, and links intact. A summarizer wants plain prose. Decide the shape of the result before you write a line of code, because every later decision depends on it.
A solid output has three parts. The main body as structured text or clean HTML. A metadata block with title, byline, publish date, canonical URL, and detected language. A fetch record with the final URL after redirects, HTTP status, content type, and the capture timestamp. Without that record you cannot explain where a quote came from six months later.
For most text pipelines, Markdown is a sensible middle ground. It keeps headings and lists, drops presentational junk, and tokenizes cleanly for embeddings. If you are feeding a vector store, chunk after extraction, not before. The goal when you extract article text is to get one trustworthy artifact per URL, then let downstream code do what it needs with it.
Fetch the public page safely
Follow redirects, record the final URL, and set a timeout. Those three habits catch most problems before they become bugs. A plain requests.get with allow_redirects=True and a 15 second timeout handles almost every public article you will meet.
Send a real User-Agent. Many sites return a stripped shell or a 403 to the default Python agent. Use a string that identifies your crawler honestly, something like ToolTraceBot/1.0 (+https://tooltrace.io). Respect robots.txt at scale. For one-off fetches of a known public article, robots is advisory, but you should still back off on 429 and 503 responses, and never retry a 4xx without changing something.
Cache responses by canonical URL and ETag. Re-extracting the same page on every run wastes bandwidth and will eventually get you rate limited. If you need JavaScript rendering, scheduled crawls, or large batches, the ToolTrace content extraction API handles redirects, retries, and headless rendering behind one endpoint. The free web page scraper is useful when you want to inspect a raw response before writing extraction code against it.
Choose static or browser rendering
Use initial HTML when it already contains the article. Most news sites, documentation portals, and WordPress blogs ship the full body in the first response. Fetching that HTML with a plain HTTP client is faster, cheaper, and more reliable than firing up a browser.
Browser rendering is for the sites that genuinely need it. React, Vue, and Next.js apps that stream content client-side will return a near-empty shell to a plain fetch. Signals you need Playwright or a headless Chrome: tiny initial HTML, visible __NEXT_DATA__ or hydration JSON, article body only appearing after an XHR fires. Our deeper read on this split lives in static vs browser rendering.
The practical rule: try static first, measure the body length, fall back to a browser only when static clearly fails. This matters at scale. Rendering a page in Chromium costs 10 to 50 times what a plain GET costs, both in wall time and compute. If you want to extract article text from thousands of URLs a day, that gap decides whether your bill is twenty dollars or two thousand.
Identify the main content region
Combine semantic elements such as article and main with heuristic scoring. The W3C HTML spec defines the article element for self-contained content and the main element for a page's primary content. When they are present and populated, use them first.
They are not always present. Fall back to density scoring: for each candidate container, count paragraph text, subtract link density and script content, then pick the highest scorer. This is the trick Mozilla's Readability.js uses, and it is why Firefox Reader View works on random blogs it has never seen before. The Python port, readability-lxml, applies the same approach server side.
Trafilatura adds a second layer: learned rules for common CMSes and news templates, with a generic fallback when no rule matches. On a mixed corpus of a thousand URLs it usually beats readability-lxml on precision and metadata recovery. Boilerpipe, originally a Java library, uses shallow text features that still work well on traditional news sites. Watch out for infinite scroll feeds and listing pages: if the URL points at /category/tech, there is no single article to extract. Confirm you landed on a detail page before scoring. JSON-LD of type NewsArticle or BlogPosting is a cheap signal.
Compare extractors in Python
Three libraries cover almost every real case: trafilatura, readability-lxml, and BeautifulSoup as the escape hatch. The pattern worth copying is to try them in order of precision and fall back on short output. Install with pip install trafilatura readability-lxml beautifulsoup4 lxml requests.
import requests
import trafilatura
from readability import Document
from bs4 import BeautifulSoup
HEADERS = {"User-Agent": "ToolTraceBot/1.0 (+https://tooltrace.io)"}
def extract(url: str) -> dict:
resp = requests.get(url, headers=HEADERS, timeout=15, allow_redirects=True)
resp.raise_for_status()
html = resp.text
# 1. Trafilatura: best precision on news and blog templates
text = trafilatura.extract(html, include_comments=False, include_tables=True)
if text and len(text) > 500:
return {"source": "trafilatura", "url": resp.url, "text": text}
# 2. Readability: broad fallback, scores by text density
doc = Document(html)
body = BeautifulSoup(doc.summary(), "lxml").get_text("\n", strip=True)
if body and len(body) > 500:
return {"source": "readability", "url": resp.url, "text": body, "title": doc.title()}
# 3. Manual: last resort, grab the article or main tag
soup = BeautifulSoup(html, "lxml")
node = soup.find("article") or soup.find("main")
body = node.get_text("\n", strip=True) if node else ""
return {"source": "manual", "url": resp.url, "text": body}Trafilatura wins most of the time on precision. Readability wins on broad compatibility across hand-written HTML and older CMSes. BeautifulSoup is where you land when both generic extractors fail and you need a site-specific rule. Log which branch hit for each URL. After a few hundred runs you will know which domains need custom handling, and that is where to spend engineering time rather than on the generic case.
Preserve structure and provenance
Keep paragraphs, headings, ordered steps, blockquotes, and images with their captions. Flattening everything to one blob of text is tempting and almost always wrong. Downstream readers lose scanability, embedding models lose paragraph boundaries, and migration tools lose the author's intent.
Map HTML to a stable intermediate format. Markdown works well for most pipelines because every renderer and every LLM understands it. If you need stricter structure, keep a slim HTML subset: h2, h3, p, ul, ol, li, blockquote, pre, code, a, img. Our guide on converting a webpage to Markdown covers the conversion rules in detail.
Preserve provenance alongside the text. Store the canonical URL from the <link rel="canonical"> tag, the publish date from meta tags or JSON-LD, the author byline, and a content hash. When you extract article text at scale, two URLs will often resolve to the same canonical, and deduplicating by canonical plus hash saves storage and prevents duplicate embeddings. Keep images as URLs rather than inlined base64, and record alt text verbatim. If an article uses pull quotes or callouts, decide once whether they belong in the main body stream. Being consistent beats being clever.
Common pitfalls and how to handle them
Cookie walls and consent banners are the first thing that breaks a scraper. European news sites commonly return a consent page until you accept GDPR cookies. The article content is sometimes present in the response, buried behind a modal, and readability-style scoring picks up the banner instead. Strip known consent containers before extraction, or match them by class names like cmp-container, didomi-popup, and qc-cmp2-container.
Paywalls are harder, and partly a legal problem. If a site uses a soft paywall, the full text often sits in the HTML with a CSS overlay. You can technically extract article text from it. You should not, unless you hold a subscription and the terms permit automated access. Hard paywalls return a truncated body or a stub, and no article text extractor can conjure the missing paragraphs.
JavaScript-rendered content fools length-based heuristics. The initial HTML looks like a valid page with a title and meta tags, but the body is a sparse shell. A generic extractor will cheerfully return eighty words of boilerplate and claim success. Compare extracted length against the article's own wordCount in JSON-LD when available, and fall back to a browser render when the ratio is off. Infinite scroll, lazy-loaded images, and AMP variants each have their own quirks. For large crawls, our writeup on web scraping for AI agents and RAG goes into the queue, retry, and dedup patterns that keep a pipeline healthy.
Validate and monitor the result
Check minimum useful length, title quality, and language. A healthy extraction has at least three hundred words for an article, a non-empty title that is not simply the site name, and a detected language that matches your corpus. Reject anything that fails these checks and route it to manual review rather than silently feeding junk into your index.
Compare against structural signals. If the page has JSON-LD of type NewsArticle with a wordCount property, your extraction should be within twenty percent of it. If it exposes an articleBody field in schema.org metadata, use that as a sanity check against your own output. Our guide on auditing on-page SEO walks through which signals are reliable and which are decorative.
Monitor extractor drift over time. Sites redesign. A template change can break a site-specific rule and silently halve your extraction yield. Log the extractor that won for each URL and the body length. A sudden drop in a per-domain average is almost always a template change, not a content change. The free article text extractor is handy for debugging a single URL by hand when a dashboard flags one. For scheduled checks across many URLs, the content extraction API returns the same fields with retries and rendering built in. Pulling the hrefs on a page before you extract article text from each is also useful, and the link extractor does that cleanly.
Work through a representative extraction
Test an editorial page that contains a headline, byline, publication date, subheadings, inline links, a quotation, and a related-content rail. Compare the source, browser view, and extracted output side by side. The result should begin with the article rather than the site navigation, retain the meaningful order, and end where the article ends.
- Confirm the title and final URL identify the same document.
- Check that paragraphs from the beginning, middle, and end are present.
- Verify headings, lists, links, code, and quotations remain understandable.
- Make sure newsletter forms, cookie notices, comments, and recommendations are absent unless explicitly required.
Use the Web Page Scraper when the job is whole-page conversion rather than article isolation, and the Content Extraction API when the workflow must run repeatedly.
Design the production extraction contract
Return a status for complete, partial, empty, access-blocked, unsupported, and failed outcomes instead of treating every HTTP success as usable content. Keep warnings beside the result so downstream systems can reject low-confidence documents before indexing or summarization.
Track extraction coverage, median word count, empty-result rate, duplicate hashes, metadata completeness, latency, and source-specific failures. Re-run a small fixture set after parser, browser, or template changes. This turns article extraction from an optimistic parser call into an observable data pipeline.
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.