# Wikipedia Knowledge & RAG Markdown Scraper (API) (`tsun_tsun/wikipedia-rag-knowledge-scraper`) Actor

Query Wikimedia REST Summary and MediaWiki Action APIs across any language edition. Outputs clean RAG Markdown, structured infobox JSON, Wikidata Q-IDs, section outlines, visible categories, and external links.

- **URL**: https://apify.com/tsun_tsun/wikipedia-rag-knowledge-scraper.md
- **Developed by:** [tsun tsun](https://apify.com/tsun_tsun) (community)
- **Categories:** AI, Agents, Developer tools
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.40 / 1,000 wikipedia articles

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Wikipedia Knowledge & RAG Markdown Scraper (API)

Extract clean Markdown articles, structured `infobox` key-value JSON maps, `wikidataId` links, section outlines, visible categories, outbound citations, thumbnails, and `revisionId` stamps from any Wikipedia language edition via Wikimedia's REST Summary API (`/api/rest_v1/page/summary/{title}`) and MediaWiki Action API (`action=parse`, `list=search`).

### Supported targets & HTML-to-Markdown pipeline

Mix desktop or mobile Wikipedia URLs (`en.wikipedia.org`, `en.m.wikipedia.org`, `/w/index.php?title=...`, non-ASCII paths), bare titles resolved under `language`, language-prefixed tokens (`de:Web_Scraping`, `th:ปัญญาประดิษฐ์`, `simple:Computer`, `zh-min-nan:Tâi-oân`, `zh-classical:孔子`), and keyword `searchQueries` in one run. Redirects deduplicate before fetching and again after MediaWiki resolves canonical titles.

A linear-time zero-DOM converter removes `<style>`, `<script>`, navboxes, maintenance banners, tables of contents, `<figure>` thumbnails, `[edit]` links, citation superscripts (`[1]`), hidden `display:none` sortkeys, and trailing boilerplate sections (`References`, `External links`, `See also`, `Notes`, `Further reading`). When both `includeMarkdown` and `includeInfobox` are `false`, `prop=text` is omitted from the MediaWiki API call to shrink response payloads.

#### Benchmarks, attribution & scope

Measured on Apify Cloud (256 MB memory), a full article run completed in `1.54 s` at `43.5 MB` peak RAM (`128 MB` minimum memory). Every request sends a compliant `Api-User-Agent`, enforces a 20-second timeout, caps responses at 5 MB, backs off on `429`/`5xx` via `Retry-After`, and flushes `OUTPUT` cleanly on abort. Wikipedia prose is licensed under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/); preserve `canonicalUrl` and `title` in downstream RAG metadata for attribution.

For multi-million-article offline corpora, download Wikimedia's static dumps from `dumps.wikimedia.org` rather than querying live APIs. This Actor reads current rendered revisions only (no edit history, talk pages, or raw Wikitext templates) and targets official Wikipedia editions rather than third-party Fandom or corporate MediaWiki sites (use [Fast Website & Sitemap Markdown Crawler for AI/RAG](https://apify.com/tsun_tsun/fast-website-markdown-crawler) for general wikis).

### Use cases

- Index clean Wikipedia background articles into vector databases with `maxMarkdownChars` caps (UTF-16 surrogate-safe boundary cuts) and `revisionId` cache invalidation.
- Enrich company, product, or person entities by joining `wikidataId` (`Q28865`), structured `infobox` fields, `coordinates`, and visible `categories` across languages.
- Attach a fast, browserless encyclopedic lookup tool to Claude Code, Claude Desktop, or Cursor over Apify MCP.
- Build aligned multilingual evaluation or training corpora across dozens of Wikipedia editions in a single run.

### Input schema & example

Provide at least one item in `pageInputs` or `searchQueries` (or both).

| Parameter | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `pageInputs` | `string[]` | *(none)* | Wikipedia URLs, plain titles, or language-prefixed tokens (`de:Web_Scraping`, `simple:Computer`). |
| `searchQueries` | `string[]` | *(none)* | Keywords searched via MediaWiki `list=search` in `language`. |
| `language` | `string` | `"en"` | Default Wikipedia edition (`en`, `de`, `fr`, `es`, `ja`, `th`, `simple`, `zh-yue`, etc.). |
| `maxResultsPerQuery` | `integer` | `5` | Max search results fetched per keyword (`1-50`). |
| `includeMarkdown` | `boolean` | `true` | Convert article body HTML to clean Markdown and compute `wordCount` and `estimatedTokens`. |
| `includeInfobox` | `boolean` | `true` | Parse infobox rows into a flat key-value JSON object. |
| `includeSections` | `boolean` | `true` | Include table-of-contents section outline (`index`, `level`, `number`, `title`, `anchor`). |
| `includeCategories` | `boolean` | `true` | Include visible categories (hidden maintenance categories excluded). |
| `includeExternalLinks` | `boolean` | `true` | Include deduplicated outbound HTTP/HTTPS links cited by the article. |
| `maxMarkdownChars` | `integer` | `0` | Character limit (`0-200000`) applied at paragraph/line/word boundaries (`0` disables). |
| `concurrency` | `integer` | `3` | Concurrent article requests (`1-6`). Keep `<= 3` for Wikimedia etiquette. |

#### Example input

```json
{
  "pageInputs": [
    "https://en.wikipedia.org/wiki/Python_(programming_language)",
    "de:Web_Scraping"
  ],
  "searchQueries": ["Model Context Protocol"],
  "language": "en",
  "maxResultsPerQuery": 3,
  "includeMarkdown": true,
  "includeInfobox": true,
  "maxMarkdownChars": 0,
  "concurrency": 3
}
```

### Dataset output

Each resolved article is pushed as one JSON record, and Key-Value Store record `OUTPUT` stores run totals along with any missing titles (`notFound`).

```json
{
  "title": "Python (programming language)",
  "displayTitle": "Python (programming language)",
  "pageId": 23862,
  "revisionId": 1387419204,
  "language": "en",
  "canonicalUrl": "https://en.wikipedia.org/wiki/Python_(programming_language)",
  "wikidataId": "Q28865",
  "pageType": "standard",
  "description": "General-purpose programming language",
  "extract": "Python is a high-level, general-purpose programming language. Its design philosophy emphasizes code readability with the use of significant indentation.",
  "thumbnailUrl": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c3/Python-logo-notext.svg/330px-Python-logo-notext.svg.png",
  "coordinates": null,
  "lastModified": "2026-11-23T14:22:18Z",
  "redirectedFrom": null,
  "infobox": {
    "Paradigm": "Multi-paradigm: object-oriented, procedural (imperative), functional, structured, reflective",
    "Designed by": "Guido van Rossum",
    "First appeared": "20 February 1991",
    "Typing discipline": "duck, dynamic, strong; optional type annotations",
    "License": "Python Software Foundation License",
    "Website": "python.org"
  },
  "sections": [
    { "index": "1", "level": 2, "number": "1", "title": "History", "anchor": "History" },
    { "index": "2", "level": 2, "number": "2", "title": "Design philosophy and features", "anchor": "Design_philosophy_and_features" },
    { "index": "3", "level": 2, "number": "3", "title": "Syntax and semantics", "anchor": "Syntax_and_semantics" }
  ],
  "categories": [
    "Python (programming language)",
    "Cross-platform software",
    "Dynamically typed programming languages",
    "Object-oriented programming languages"
  ],
  "externalLinks": [
    "https://www.python.org/"
  ],
  "markdown": "**Python** is a high-level, general-purpose programming language...\n\n## History\n\nPython was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde & Informatica (CWI) in the Netherlands.",
  "markdownTruncated": false,
  "wordCount": 7814,
  "estimatedTokens": 12490,
  "sourceInput": "https://en.wikipedia.org/wiki/Python_(programming_language)",
  "matchedQuery": null,
  "scrapedAt": "2026-11-24T22:08:14.517Z"
}
```

#### Output fields

| Field | Type | Description |
| :--- | :--- | :--- |
| `title` / `displayTitle` | `string` | Canonical article title after redirects and plain-text display title. |
| `pageId` / `revisionId` | `number \| null` | MediaWiki page ID and latest revision ID (`revid`) for cache invalidation. |
| `language` / `canonicalUrl` | `string` | Wikipedia edition code and canonical desktop URL. |
| `wikidataId` | `string \| null` | Wikidata item ID (e.g. `Q28865`) for cross-language entity joins. |
| `pageType` / `description` | `string \| null` | Wikimedia REST page type (`standard`, `disambiguation`) and short description. |
| `extract` / `thumbnailUrl` | `string \| null` | Plain-text lead summary and main thumbnail URL if available. |
| `coordinates` | `object \| null` | `{ lat, lon }` coordinates for geographic entities. |
| `lastModified` / `redirectedFrom` | `string \| null` | Latest revision timestamp and requested alias title if redirected. |
| `infobox` | `object` | Flat key-value map extracted from the article's infobox (`{}` if none). |
| `sections` | `object[]` | Section list with `index`, `level`, `number`, `title`, and `anchor`. |
| `categories` | `string[]` | Visible Wikipedia categories with hidden maintenance categories removed. |
| `externalLinks` | `string[]` | Deduplicated outbound HTTP/HTTPS links referenced by the article. |
| `markdown` | `string \| null` | Cleaned article Markdown (`null` when `includeMarkdown: false`). |
| `markdownTruncated` | `boolean` | `true` when `markdown` was cut to fit `maxMarkdownChars`. |
| `wordCount` / `estimatedTokens` | `number` | Word count and approximate tokens (`Math.ceil(markdown.length / 4)`). |
| `sourceInput` / `matchedQuery` | `string`, `string \| null` | Originating `pageInputs` item or `search:<query>` and matched search query. |
| `scrapedAt` | `string` | ISO 8601 UTC extraction timestamp. |

### Pay-Per-Event pricing

Pay-Per-Event billing on `article-scraped` with **$0 actor-start fee** and **$0 proxy fees**. Missing/404 titles and duplicate redirects are logged in `OUTPUT` and billed `$0`.

| Event (Apify Store Label) | Free / 1k | Bronze (-10%) | Silver (-20%) | Gold+ (-30%) |
| :--- | :--- | :--- | :--- | :--- |
| Wikipedia article | `$2.00` | `$1.80` | `$1.60` | `$1.40` |

`Gold+` includes Gold, Platinum, and Diamond plans (all `-30%`, or `$0.0014` per article). Apify's **$5 monthly free credit** covers **2,500 Wikipedia articles/month** on the Free plan.

### Integrations (MCP, SDKs & cURL)

#### Claude Code (MCP)

```bash
claude mcp add --transport http apify-wikipedia \
  "https://mcp.apify.com/?tools=tsun_tsun/wikipedia-rag-knowledge-scraper" \
  --header "Authorization: Bearer $APIFY_TOKEN"
```

#### Claude Desktop, Cursor & Windsurf (MCP)

```json
{
  "mcpServers": {
    "apify-wikipedia": {
      "url": "https://mcp.apify.com/?tools=tsun_tsun/wikipedia-rag-knowledge-scraper",
      "headers": {
        "Authorization": "Bearer YOUR_APIFY_TOKEN"
      }
    }
  }
}
```

#### JavaScript / TypeScript (`apify-client`)

```javascript
import { ApifyClient } from 'apify-client';

const client = new ApifyClient({ token: process.env.APIFY_TOKEN });
const run = await client.actor('tsun_tsun/wikipedia-rag-knowledge-scraper').call({
  pageInputs: ['https://en.wikipedia.org/wiki/Python_(programming_language)', 'de:Web_Scraping'],
  searchQueries: ['Model Context Protocol'],
  maxResultsPerQuery: 3,
});
const { items } = await client.dataset(run.defaultDatasetId).listItems();
for (const article of items) {
  console.log(article.title, article.wikidataId, article.estimatedTokens);
}
```

#### Python (`apify-client`)

```python
import os
from apify_client import ApifyClient

client = ApifyClient(os.environ["APIFY_TOKEN"])
run = client.actor("tsun_tsun/wikipedia-rag-knowledge-scraper").call(
    run_input={
        "pageInputs": ["https://en.wikipedia.org/wiki/Python_(programming_language)"],
        "searchQueries": ["Model Context Protocol"],
        "maxResultsPerQuery": 3,
        "maxMarkdownChars": 16000,
    }
)
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item["title"], item["wikidataId"], item["wordCount"])
```

#### cURL

```bash
curl -X POST "https://api.apify.com/v2/acts/tsun_tsun~wikipedia-rag-knowledge-scraper/run-sync-get-dataset-items" \
  -H "Authorization: Bearer $APIFY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "pageInputs": ["https://en.wikipedia.org/wiki/Python_(programming_language)"],
    "searchQueries": ["Model Context Protocol"],
    "maxResultsPerQuery": 2
  }'
```

### Frequently asked questions

#### How are formatted numbers and hidden sortkeys handled inside `infobox`?

Infobox cells strip inline `<style>` tags, `[1]` citation superscripts, and hidden `display:none` sortkeys (such as `{{Birth date and age}}` sorting dates) while keeping numeric commas intact (e.g. `8,804,190` and `$391,035,000,000`). Articles without an infobox return `{}`.

#### Why does `concurrency` default to `3`?

Wikimedia API guidelines ask automated clients to keep parallel request volume low and send an identifying `Api-User-Agent`. Keeping `concurrency` at `3` avoids `HTTP 429` throttling while finishing typical batches in a couple of seconds.

#### How can I check if an article changed since my last RAG sync?

Store `revisionId` alongside your embeddings. If you want lightweight metadata checks before re-embedding Markdown, run with `includeMarkdown: false` and `includeInfobox: false` so `prop=text` is skipped.

#### Are misspelled titles or duplicate redirects billed?

No. HTTP 404 responses, MediaWiki `missingtitle` errors, and aliases redirecting to an already-collected page are logged under `OUTPUT.notFound` or `OUTPUT.skippedDuplicates` at `$0`.

### Related Actors

Companion lightweight API Actors and free workflow templates in the [Apify Automation Toolkit](https://pie527645-cloud.github.io/apify-automation-toolkit/):

| Actor | Best paired for |
| :--- | :--- |
| [Fast Website & Sitemap Markdown Crawler for AI/RAG](https://apify.com/tsun_tsun/fast-website-markdown-crawler) | Crawl official documentation and external reference sites cited in `externalLinks`. |
| [Google News & Universal RSS/Atom Feed Scraper](https://apify.com/tsun_tsun/google-news-rss-intelligence) | Combine live news streams with background Wikipedia entity summaries. |
| [Substack Newsletter & Archive Scraper (Markdown)](https://apify.com/tsun_tsun/substack-intelligence-scraper) | Ingest long-form newsletter archives into the same Markdown RAG index. |
| [Apple Podcasts & RSS Scraper (Host Emails & Shows)](https://apify.com/tsun_tsun/apple-podcasts-rss-scraper) | Pull podcast shows, host emails, and episode show notes. |
| [Apple App Store & Reviews Scraper (iOS Apps & Ratings)](https://apify.com/tsun_tsun/app-store-reviews-scraper) | Pair company and product Wikipedia profiles with live iOS app ratings and reviews. |
| [Website Contact, Email MX/DMARC & Tech Stack Enricher](https://apify.com/tsun_tsun/website-lead-tech-enricher) | Enrich official domains from infobox `Website` fields with contact and DNS/tech signals. |

# Changelog

This Actor's version history is a separate document: https://apify.com/tsun_tsun/wikipedia-rag-knowledge-scraper/changelog.md

# Actor input Schema

## `pageInputs` (type: `array`):

Direct Wikipedia targets to scrape. Accepts full Wikipedia URLs (e.g. 'https://en.wikipedia.org/wiki/Python\_(programming_language)', 'https://simple.wikipedia.org/wiki/Computer'), plain article titles resolved against the default language (e.g. 'Web scraping'), or language-prefixed tokens (e.g. 'de:Web_Scraping', 'th:ปัญญาประดิษฐ์', 'zh-min-nan:Tâi-oân'). At least one of pageInputs or searchQueries must be provided.

## `searchQueries` (type: `array`):

Keyword search queries executed against MediaWiki's search API (list=search) in the configured language edition (e.g. 'Model Context Protocol', 'Retrieval-augmented generation'). Matched articles are deduplicated and scraped. At least one of pageInputs or searchQueries must be provided.

## `language` (type: `string`):

Default Wikipedia language subdomain used for searchQueries and plain article titles without a URL or language prefix (e.g. 'en', 'de', 'fr', 'es', 'ja', 'th', 'simple', 'zh-yue', 'zh-min-nan', 'zh-classical'). Overridden by language-prefixed tokens or full Wikipedia URLs.

## `maxResultsPerQuery` (type: `integer`):

Maximum number of Wikipedia articles fetched per keyword in searchQueries (1 to 50).

## `includeMarkdown` (type: `boolean`):

Convert the article body into clean Markdown with headings, lists, blockquotes, tables, and code blocks while stripping navboxes, infoboxes, edit links, reference superscripts, and trailing citation boilerplate.

## `includeInfobox` (type: `boolean`):

Parse the article's Wikipedia infobox table into a key-value JSON object with reference markers, hidden sortkeys, and inline styles removed.

## `includeSections` (type: `boolean`):

Include the article's table-of-contents section hierarchy (index, level, number, title, anchor).

## `includeCategories` (type: `boolean`):

Include visible Wikipedia categories with hidden maintenance categories filtered out and underscores replaced by spaces.

## `includeExternalLinks` (type: `boolean`):

Include deduplicated outbound external HTTP/HTTPS URLs referenced by the article.

## `maxMarkdownChars` (type: `integer`):

Optional character cap applied at a word or paragraph boundary for token-budgeted RAG pipelines. Set to 0 to return the complete article Markdown without truncation.

## `concurrency` (type: `integer`):

Number of Wikipedia articles processed concurrently (1 to 6). Keep at 3 or lower to stay polite to Wikimedia APIs and avoid HTTP 429 rate limits.

## Actor input object example

```json
{
  "pageInputs": [
    "https://en.wikipedia.org/wiki/Python_(programming_language)",
    "de:Web_Scraping"
  ],
  "searchQueries": [
    "Model Context Protocol"
  ],
  "language": "en",
  "maxResultsPerQuery": 5,
  "includeMarkdown": true,
  "includeInfobox": true,
  "includeSections": true,
  "includeCategories": true,
  "includeExternalLinks": true,
  "maxMarkdownChars": 16000,
  "concurrency": 3
}
```

# Actor output Schema

## `summary` (type: `string`):

JSON summary with articles scraped, missing titles (notFound), duplicate redirects skipped, total words/tokens, and runtime.

## `articles` (type: `string`):

Structured Wikipedia article records containing clean RAG Markdown, infobox JSON, Wikidata IDs, sections, categories, and thumbnails.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "pageInputs": [
        "https://en.wikipedia.org/wiki/Python_(programming_language)"
    ],
    "searchQueries": [
        "Model Context Protocol"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("tsun_tsun/wikipedia-rag-knowledge-scraper").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "pageInputs": ["https://en.wikipedia.org/wiki/Python_(programming_language)"],
    "searchQueries": ["Model Context Protocol"],
}

# Run the Actor and wait for it to finish
run = client.actor("tsun_tsun/wikipedia-rag-knowledge-scraper").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "pageInputs": [
    "https://en.wikipedia.org/wiki/Python_(programming_language)"
  ],
  "searchQueries": [
    "Model Context Protocol"
  ]
}' |
apify call tsun_tsun/wikipedia-rag-knowledge-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,tsun_tsun/wikipedia-rag-knowledge-scraper"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/WaMIw9Zy8gKAQ6jqM/builds/79hbjgZcGzzwVfyYv/openapi.json
