Disclosure: I built the Apify Actor mentioned near the end of this post.
To get a whole Wikipedia article as plain text, call the MediaWiki Action API with action=query&prop=extracts&explaintext=1&titles=<title>. It returns the full article with section headings written as == Heading ==, but only for one article per request: if you pass several titles, Wikipedia lowers the limit to 1 and the other pages come back with no text. Add exintro=1 and you can get up to 20 intros at once, but never 20 full articles. No API key is needed; a descriptive User-Agent is.
This post shows standard-library Python that fetches full articles for a list of titles, splits them into section chunks, drops the reference sections, and puts the source URL and the CC BY-SA licence on every chunk, which is what you want before the text goes into a vector store or an LLM dataset. A hosted option is at the end.
Which Wikipedia API returns the article text?
There are three common options, and only one gives you plain text for the whole article:
| Endpoint | What you get | Plain text? |
|---|---|---|
/w/api.php?action=query&prop=extracts&explaintext=1 (TextExtracts) |
Whole article, or intro only with exintro=1
|
Yes |
/api/rest_v1/page/summary/{title} |
Intro summary only (337 characters for Tokyo when I checked) | Yes, intro only |
/w/rest.php/v1/page/{title} |
The wikitext source plus a license field |
No, it is markup |
You can also parse HTML or wikitext yourself, but templates, infoboxes and footnotes make that a project of its own. For "give me the readable text", TextExtracts with explaintext is the shortest path.
Why does only the first article have text?
This is the trap behind a lot of "my extract is missing" questions. I asked for three full articles in one request:
curl -s -A 'devto-example-script/1.0 (contact: you@example.com)' \
'https://en.wikipedia.org/w/api.php?action=query&format=json&formatversion=2&prop=extracts&explaintext=1&redirects=1&titles=Ada%20Lovelace|Tokyo|UK'
The response (2026-12-01) had this warning and a continue block:
{"warnings": {"extracts": {"warnings": "\"exlimit\" was too large for a whole article extracts request, lowered to 1."}},
"continue": {"excontinue": 1, "continue": "||"}}
Ada Lovelace came back with 40,824 characters of text; Tokyo and United Kingdom had no extract key at all. With exintro=1 added, all three had text (3,186, 3,760 and 3,628 characters). The API's own parameter info confirms the numbers: exlimit maxes out at 20, and the docs say multiple extracts are only returned when exintro is set.
So the rule is simple: intros can be batched, whole articles cannot. For full text, send one title per request (or follow excontinue, which amounts to the same thing).
What does the plain text look like?
With the default exsectionformat=wiki, headings keep their wiki level, which is exactly what you need to chunk by section:
== Biography ==
=== Childhood ===
=== Adult years ===
...
== See also ==
== References ==
=== Citations ===
== External links ==
Things I saw in the output, and what the TextExtracts documentation warns about:
- Tables and infoboxes are not included. Tokyo's plain text has no "Climate data" table.
-
Formatting inside formulas is lost. The intro of Pythagorean theorem comes out as
a2+b2=c2; the superscripts are gone. The docs also note that formulas can disappear and that inline images are stripped. - Reference sections are included as text. "References", "Further reading" and "External links" arrive as lists of titles and URLs. For RAG, drop them.
- Some headings have no text under them (a parent heading directly followed by its first subheading). Skip empty chunks.
- The docs list a few more plain-text edge cases: citations not always stripped, and new lines sometimes dropped around lists.
How do I get full text for a list of articles in Python?
Standard library only (tested with Python 3.9.6). It asks each Wikipedia for its licence once, then fetches one article per request with redirects resolved, about one request per second:
import json
import re
import time
import urllib.parse
import urllib.request
import urllib.error
LANG = "en"
API = f"https://{LANG}.wikipedia.org/w/api.php"
# Wikimedia asks every client to send a descriptive User-Agent with a contact.
UA = "devto-example-script/1.0 (contact: you@example.com)"
PAUSE = 1.0 # seconds between requests
DROP = {"See also", "Notes", "Explanatory notes", "References", "Citations",
"Bibliography", "Further reading", "External links", "Sources"}
def api(**params):
params.update(format="json", formatversion="2", maxlag="5")
url = API + "?" + urllib.parse.urlencode(params)
req = urllib.request.Request(url, headers={"User-Agent": UA})
for attempt in range(4):
try:
with urllib.request.urlopen(req, timeout=30) as resp:
data = json.load(resp)
time.sleep(PAUSE)
if data.get("error", {}).get("code") == "maxlag":
time.sleep(5)
continue
return data
except urllib.error.HTTPError as e:
if e.code in (429, 503) and attempt < 3:
time.sleep(int(e.headers.get("Retry-After", 5)))
continue
raise
raise RuntimeError("gave up after retries")
def licence():
info = api(action="query", meta="siteinfo", siprop="rightsinfo")
return info["query"]["rightsinfo"] # {"url": ..., "text": ...}
def fetch_article(title):
# One title per request: whole-article extracts are limited to 1 page.
data = api(action="query", titles=title, redirects="1",
prop="extracts|info", explaintext="1", inprop="url")
page = data["query"]["pages"][0]
if page.get("missing") or page.get("invalid"):
return None
redirects = data["query"].get("redirects", [])
page["redirected_from"] = redirects[0]["from"] if redirects else None
return page
def split_sections(text):
"""Yield (heading_path, body) using the '== Heading ==' lines."""
path, body = ["Introduction"], []
for line in text.split("\n"):
m = re.fullmatch(r"(=+) (.+?) \1", line.strip())
if m:
yield " > ".join(path), "\n".join(body).strip()
level = len(m.group(1)) - 1 # '==' is level 1
path = path[:level - 1] + [m.group(2)]
body = []
else:
body.append(line)
yield " > ".join(path), "\n".join(body).strip()
def chunks_for(title, lic):
page = fetch_article(title)
if page is None:
print(f"skip {title!r}: no such article")
return []
rows = []
for section, body in split_sections(page["extract"]):
if not body or section.split(" > ")[0] in DROP:
continue
rows.append({
"title": page["title"],
"section": section,
"text": body,
"url": page["fullurl"],
"revid": page["lastrevid"],
"license": lic["text"],
"license_url": lic["url"],
"attribution": f'"{page["title"]}" from Wikipedia, by Wikipedia '
f'contributors, {page["fullurl"]}, {lic["text"]}. '
"Converted to plain text and split by section.",
})
print(f'{page["title"]} (from {page["redirected_from"]!r}): '
f'{len(page["extract"])} chars, {len(rows)} chunks kept')
return rows
if __name__ == "__main__":
titles = ["Ada Lovelace", "UK", "Pythagorean theorem", "Asdfqwerty zxcv"]
lic = licence()
rows = [r for t in titles for r in chunks_for(t, lic)]
with open("wikipedia_chunks.jsonl", "w", encoding="utf-8") as f:
for r in rows:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
print(len(rows), "chunks written")
first = dict(rows[1], text=rows[1]["text"][:80] + "...")
print(json.dumps(first, indent=2, ensure_ascii=False))
Output from my run on 2026-12-01 at 08:35 UTC (5 requests, about 10 seconds; a second run a few seconds later printed exactly the same):
Ada Lovelace (from None): 40824 chars, 21 chunks kept
United Kingdom (from 'UK'): 95588 chars, 45 chunks kept
Pythagorean theorem (from None): 45166 chars, 35 chunks kept
skip 'Asdfqwerty zxcv': no such article
101 chunks written
{
"title": "Ada Lovelace",
"section": "Biography > Childhood",
"text": "Lord Byron expected his child to be a \"glorious boy\" and was disappointed when L...",
"url": "https://en.wikipedia.org/wiki/Ada_Lovelace",
"revid": 1386418140,
"license": "Creative Commons Attribution-Share Alike 4.0",
"license_url": "https://creativecommons.org/licenses/by-sa/4.0/deed.en",
"attribution": "\"Ada Lovelace\" from Wikipedia, by Wikipedia contributors, https://en.wikipedia.org/wiki/Ada_Lovelace, Creative Commons Attribution-Share Alike 4.0. Converted to plain text and split by section."
}
A few notes on the choices:
-
Redirects.
UKresolved toUnited Kingdombecause ofredirects=1. Keepredirected_fromif your users search by the short name. If two inputs redirect to the same article, deduplicate bytitlebefore indexing. -
Section path. The chunk's
sectionis a breadcrumb (Work > First published computer program > Controversy over contribution). Prepending it to the text before embedding helps retrieval, because a subsection's body often does not repeat the article's subject. - Chunk size. Sections vary a lot: in this run Ada Lovelace's chunks ranged from 239 to 5,044 characters. If your embedding model has a small window, split long sections further on blank lines.
-
revid. Store it. On the next refresh, compare it withprop=info'slastrevid(which can be batched, 50 titles per request) and re-fetch only the articles that changed. -
Errors. The 429/503 retry with
Retry-Afterand themaxlagpause follow Wikimedia's API etiquette. I did not hit either branch in my runs, so treat that part as untested.
What licence applies to Wikipedia text in an LLM or RAG dataset?
Wikipedia text is licensed under Creative Commons Attribution-ShareAlike 4.0 (the script reads the exact licence from meta=siteinfo&siprop=rightsinfo rather than hard-coding it). If you republish the text, including showing retrieved passages to users, you need to credit the contributors, link the source and the licence, say that you changed it, and share adapted text under the same licence. That is why every chunk above carries url, license_url and an attribution line: when a chunk is cited in an answer, the credit travels with it. This is a summary, not legal advice; read the licence terms for your use case.
Should I use the API or a Wikipedia dump?
It depends on how many articles you need:
- Hundreds to a few thousand chosen articles: the API is fine. At one request per second, 1,000 articles is about 17 minutes.
-
All of a language edition: do not loop over the API. Use the database dumps or a pre-processed dataset such as
wikimedia/wikipediaon Hugging Face, and use the API only to refresh the articles that changed.
What if I would rather not run and maintain the script?
I built an Apify Actor, Wikipedia Scraper – Articles, Wikidata & Pageviews, that calls the same public Wikimedia APIs. It is not affiliated with or endorsed by the Wikimedia Foundation. There is a ready-made example for this exact use: Wikipedia full text as plain text for LLM and RAG datasets. Its input:
{
"titles": [
"Large language model",
"Transformer (deep learning architecture)",
"Retrieval-augmented generation",
"Vector database",
"Prompt engineering"
],
"language": "en",
"includeFullText": true,
"includePageviews": false,
"maxItems": 50
}
What it does, from its README:
- One row per article with
extract(intro), and withincludeFullTextafullTextfield: the whole article as plain text, headings kept as== Heading ==. It does not split into chunks for you; usesplit_sections()above onfullTextif you need that. - Every row has
sourceUrl,license,licenseUrland a ready-madeattributionline, pluslastRevisionIdfor change checks. - Takes titles, article URLs in any language, search keywords or categories (with subcategories up to depth 5). Redirects are resolved and duplicates returned once.
- Masks e-mail addresses and phone numbers in article text on a best-effort basis.
- Price: US$1.00 per 1,000 articles plus US$0.0005 per run start; full text does not cost extra. Apify's free plan (US$5 of usage a month) covers about 5,000 articles.
- Speed: full text needs one request per article, and the Actor stays at 2 requests per second across all Wikimedia sites. One run lasts at most 20 minutes, so keep full-text runs to roughly 1,000 articles or split them.
FAQ
Can the Wikipedia API return the full text of several articles in one request?
No. With prop=extracts and no exintro, the API lowers exlimit to 1 and returns a warning: only the first page gets text. Send one title per request for whole articles. Intros (exintro=1) can be batched up to 20 per request.
How do I get Wikipedia text without HTML or wiki markup?
Add explaintext=1 to a prop=extracts query on https://<lang>.wikipedia.org/w/api.php. The result is plain text with headings as == Heading ==. Tables, infoboxes and images are not included, and formula formatting such as superscripts is lost.
How do I split a Wikipedia article into sections?
Keep the default exsectionformat=wiki and split on lines that match == Heading ==, using the number of = signs for the heading level. Skip empty sections and drop "References", "External links" and similar sections before indexing.
Do I need an API key for the Wikipedia API?
No. Reading is open without an account or key. Send a descriptive User-Agent header with contact information, keep to about one request at a time, and back off when the API returns 429 or asks you to wait.
Can I use Wikipedia text to build an LLM or RAG dataset?
The text is under CC BY-SA 4.0, which allows reuse, including commercial use, if you credit the contributors, link the source and licence, note your changes, and share adapted text under the same licence. Keep the source URL and licence with every chunk so you can show the credit wherever the text appears.
What is the difference between exintro and full text?
exintro=1 returns only the lead section before the first heading (about 3,000–4,000 characters for the articles above), and it can be batched. Without it you get the whole article, one per request; Ada Lovelace was 40,824 characters.
How do you chunk Wikipedia for retrieval: by section, by fixed token windows, or something else?
Disclosure: I built the Apify Actor mentioned in this post.
Top comments (0)