# Stack Overflow & Stack Exchange Q\&A Scraper | 2Space (`2space/stackoverflow-qa-scraper`) Actor

Fast Stack Overflow and Stack Exchange Q\&A scraper for AI coding agents and RAG. Scrapes questions, accepted and top-voted answers, code blocks, clean Markdown, vote scores, and tags.

- **URL**: https://apify.com/2space/stackoverflow-qa-scraper.md
- **Developed by:** [2Space Group](https://apify.com/2space) (community)
- **Categories:** Developer tools, AI, MCP servers
- **Features:** Limited permissions
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.70 / 1,000 q\&a thread scraped

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/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

## Stack Overflow & Stack Exchange Q\&A Scraper | 2Space

> **Built by 2Space Group** · Fast, zero-browser **Stack Overflow scraper**, **Stack Exchange Q\&A scraper**, **developer Q\&A API**, and **code snippet extractor** built for AI coding assistants, RAG knowledge bases, and MCP clients.

[![Apify Actor](https://img.shields.io/badge/Apify-stackoverflow--qa--scraper-00C853?style=flat-square)](https://apify.com/reminiscent_medaka/stackoverflow-qa-scraper)
[![MCP Ready](https://img.shields.io/badge/MCP-Ready-2563EB?style=flat-square)](https://mcp.apify.com)
[![Zero Browser](https://img.shields.io/badge/Runtime-Pure%20HTTP%20%2B%20Cheerio-7C3AED?style=flat-square)](https://apify.com/reminiscent_medaka/stackoverflow-qa-scraper)

Need a reliable **Stack Overflow scraper** or **Stack Exchange Q\&A scraper** to collect verified programming solutions, error resolutions, and reusable code snippets? This lightweight **Stack Overflow API scraper** queries the official Stack Exchange v2.3 search and batch answers endpoints over pure HTTP, converting HTML question and answer bodies into clean Markdown with extracted fenced `codeBlocks`, acceptance flags, vote scores, view counts, and topic tags—with zero headless browsers and zero external LLM API keys.

***

### Key Capabilities & Use Cases

- **RAG & AI Coding Assistants:** Feed clean, Markdown-formatted questions, `acceptedAnswerMarkdown`, and `topAnswersMarkdown` directly into vector databases, ChatGPT, Claude, or Cursor workflows.
- **Automated Code Snippet Extraction:** Every `<pre><code>` snippet across the question and top answers is cleanly extracted, entity-decoded, and deduplicated into `codeBlocks: string[]`.
- **Multi-Site Stack Exchange Support:** Works across `stackoverflow`, `serverfault`, `superuser`, `askubuntu`, `dba`, `math`, and any other Stack Exchange network site slug.
- **High-Speed Pure HTTP Architecture:** Runs in seconds using native `fetch` and `cheerio` without Playwright, Puppeteer, or proxy overhead, respecting Stack Exchange backoff headers automatically.
- **Zero-Config `{}` Ready:** Passing `{}` runs immediately with built-in defaults (`query: "typescript"`, `tags: ["node.js"]`, `site: "stackoverflow"`, `maxItems: 10`), returning verified Q\&A threads in under 10 seconds.
- **No Data, No Charge (Pay-Per-Event):** Uses the single `qa-thread-scraped` event (`count: 1`), charged **only after** a validated Q\&A thread is pushed to the dataset, protected by `maxItems` and `maxCostUsd` spending caps.

***

### Input Parameters

| Field | Type | Default | Description |
|---|---|---|---|
| `query` | `string` | `"typescript"` | Free-text search query for Stack Exchange advanced search. Leave empty when filtering strictly by `tags`. |
| `tags` | `string[]` | `["node.js"]` | Stack Exchange tag filters combined with AND semantics (e.g., `["node.js", "typescript"]`). |
| `site` | `string` | `"stackoverflow"` | Target Stack Exchange site slug (e.g., `stackoverflow`, `serverfault`, `superuser`, `askubuntu`, `dba`). |
| `sortBy` | `string` | `"votes"` | Search sort order: `votes`, `relevance`, or `creation`. |
| `includeTopAnswers` | `boolean` | `true` | Batch-fetch answers and populate `acceptedAnswerMarkdown`, `topAnswersMarkdown`, and answer code blocks. |
| `maxAnswersPerQuestion` | `integer` | `2` | Maximum number of top answers (accepted answer first, then highest score) included in `topAnswersMarkdown`. |
| `maxItems` | `integer` | `10` | Hard cap on deduplicated Q\&A threads pushed and billed per run. |
| `maxCostUsd` | `number` | `0.25` | Pre-charge spending safety cap in USD for Pay-Per-Event billing. |

***

### Example JSON Output

Each item stored in the default dataset follows a clean, agent-ready structure:

````json
{
  "questionId": 33535879,
  "site": "stackoverflow",
  "title": "How to run TypeScript files from command line?",
  "questionUrl": "https://stackoverflow.com/questions/33535879/how-to-run-typescript-files-from-command-line",
  "isAnswered": true,
  "score": 831,
  "viewCount": 1288255,
  "answerCount": 29,
  "acceptedAnswerId": 33536053,
  "tags": ["node.js", "typescript"],
  "author": "Community Developer",
  "createdAt": "2015-11-05T02:54:39.000Z",
  "lastActivityAt": "2026-10-14T11:20:00.000Z",
  "questionMarkdown": "How can I execute a `.ts` file directly from the command line in Node.js?",
  "acceptedAnswerMarkdown": "Install `tsx` and run the TypeScript file directly:\n\n```bash\nnpx tsx index.ts\n```",
  "topAnswersMarkdown": "### Answer 1 (Score: 1095, Accepted)\n\nInstall `tsx` and run the TypeScript file directly:\n\n```bash\nnpx tsx index.ts\n```",
  "codeBlocks": ["npx tsx index.ts"],
  "extractedAt": "2026-12-01T08:15:00.000Z"
}
````

A full execution summary is also persisted to the default Key-Value Store under `RUN_DIAGNOSTICS`, recording `questionsFetched`, `answersFetched`, `pushedCount`, `chargedCount`, `quotaRemaining`, and `costCapReached`.

***

### MCP & AI Agent Integration (ChatGPT, Claude, Cursor)

Connect `reminiscent_medaka/stackoverflow-qa-scraper` directly to ChatGPT, Claude Desktop, Cursor, or any MCP-compatible coding assistant in seconds:

1. **Apify MCP Endpoint URL:**
   ```text
   https://mcp.apify.com/?actors=reminiscent_medaka/stackoverflow-qa-scraper
   ```

2. **Cursor / Claude Desktop (`mcpServers` configuration):**
   ```json
   {
     "mcpServers": {
       "apify-stackoverflow-qa": {
         "url": "https://mcp.apify.com/?actors=reminiscent_medaka/stackoverflow-qa-scraper",
         "headers": {
           "Authorization": "Bearer YOUR_APIFY_TOKEN"
         }
       }
     }
   }
   ```
   Example prompt for your assistant: *"Use stackoverflow-qa-scraper to fetch the top 5 highest-voted Stack Overflow Q\&A threads for Next.js App Router caching with accepted answers."*

3. **Synchronous REST API (n8n, Make, Zapier, Custom Pipelines):**
   ```text
   POST https://api.apify.com/v2/acts/reminiscent_medaka~stackoverflow-qa-scraper/run-sync-get-dataset-items?token=YOUR_APIFY_TOKEN
   ```

***

### Pricing & No Data, No Charge Guarantee

- **Event:** `qa-thread-scraped` (`count: 1` per validated pushed Q\&A thread).
- **No Data, No Charge:** If a query matches zero questions or fails validation, `Actor.charge()` is never called.
- **Budget Controls:** Both `maxItems` and `maxCostUsd` are checked before pushing or charging, and Apify's `eventChargeLimitReached` stops execution cleanly as soon as your spending cap is met.

***

### Issues & Support

Need help with a specific Stack Exchange site slug, tag filter, or Markdown formatting edge case? Open a ticket on the Actor's **Issues** tab in Apify Console (`https://apify.com/reminiscent_medaka/stackoverflow-qa-scraper/issues`) and attach your anonymized input and `RUN_DIAGNOSTICS` output.

***

### More Tools by 2Space Group

| Actor | Use Case | Link |
|---|---|---|
| **Stack Overflow & Stack Exchange Q\&A Scraper** | Clean Markdown Q\&A threads & code blocks for AI agents | [View Actor](https://apify.com/reminiscent_medaka/stackoverflow-qa-scraper) |
| **2Space Group Actor Suite** | Browse all MCP-ready scrapers and developer data tools | [View Profile](https://apify.com/reminiscent_medaka) |

# Actor input Schema

## `query` (type: `string`):

Free-text search query for Stack Exchange advanced search (e.g., 'typescript', 'async await error handling', 'docker compose'). Leave empty when filtering strictly by tags.

## `tags` (type: `array`):

Stack Exchange tag filters (e.g., \['node.js', 'typescript']). Multiple tags are combined with AND semantics by the Stack Exchange search API.

## `site` (type: `string`):

Target Stack Exchange site slug (e.g., 'stackoverflow', 'serverfault', 'superuser', 'askubuntu', 'dba', 'math').

## `sortBy` (type: `string`):

Ordering applied to Stack Exchange search results.

## `includeTopAnswers` (type: `boolean`):

When enabled, batch-fetches answers for matched questions and extracts acceptedAnswerMarkdown, topAnswersMarkdown, and answer code blocks.

## `maxAnswersPerQuestion` (type: `integer`):

Maximum number of top answers (ordered with accepted answer first, then highest score) to include in topAnswersMarkdown.

## `maxItems` (type: `integer`):

Hard cap on the maximum number of deduplicated Q\&A threads to push and charge.

## `maxCostUsd` (type: `number`):

Pre-charge spending safety cap in USD for Pay-Per-Event billing.

## Actor input object example

```json
{
  "query": "typescript",
  "tags": [
    "node.js"
  ],
  "site": "stackoverflow",
  "sortBy": "votes",
  "includeTopAnswers": true,
  "maxAnswersPerQuestion": 2,
  "maxItems": 10,
  "maxCostUsd": 0.25
}
```

# Actor output Schema

## `overview` (type: `string`):

Dataset items containing extracted Stack Overflow & Stack Exchange Q\&A threads.

# 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 = {
    "query": "typescript",
    "tags": [
        "node.js"
    ],
    "site": "stackoverflow",
    "sortBy": "votes",
    "includeTopAnswers": true,
    "maxAnswersPerQuestion": 2,
    "maxItems": 10,
    "maxCostUsd": 0.25
};

// Run the Actor and wait for it to finish
const run = await client.actor("2space/stackoverflow-qa-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 = {
    "query": "typescript",
    "tags": ["node.js"],
    "site": "stackoverflow",
    "sortBy": "votes",
    "includeTopAnswers": True,
    "maxAnswersPerQuestion": 2,
    "maxItems": 10,
    "maxCostUsd": 0.25,
}

# Run the Actor and wait for it to finish
run = client.actor("2space/stackoverflow-qa-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 '{
  "query": "typescript",
  "tags": [
    "node.js"
  ],
  "site": "stackoverflow",
  "sortBy": "votes",
  "includeTopAnswers": true,
  "maxAnswersPerQuestion": 2,
  "maxItems": 10,
  "maxCostUsd": 0.25
}' |
apify call 2space/stackoverflow-qa-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,2space/stackoverflow-qa-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/UNMbXv1GrsKJrR2Ui/builds/Oiw4rC8HRyuuiX3dP/openapi.json
