# Stack Overflow & Stack Exchange Q\&A Scraper API (`f0rty7even/stackexchange-scraper`) Actor

Scrape questions and answers from Stack Overflow and any Stack Exchange site via the official API. Filter by tag, keyword, and sort. Clean text output, perfect for LLM/RAG datasets and dev research.

- **URL**: https://apify.com/f0rty7even/stackexchange-scraper.md
- **Developed by:** [Michael Yousrie](https://apify.com/f0rty7even) (community)
- **Categories:** Developer tools, AI
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $5.00 / 1,000 question scrapeds

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

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

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
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.
Actors are written with capital "A".

## 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.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## Stack Overflow & Stack Exchange Q\&A Scraper — Questions & Answers API

**Scrape questions and answers from Stack Overflow — or any Stack Exchange site — into clean, structured data.** This scraper uses the **official Stack Exchange API** to pull questions (with full body, tags, scores, and metadata) and, optionally, their **answers** — so you get ready-to-use **Q\&A pairs** for LLM/RAG datasets, developer research, or trend analysis. HTML is stripped to clean text.

Works across the whole Stack Exchange network: `stackoverflow`, `superuser`, `serverfault`, `askubuntu`, `math.stackexchange`, `datascience`, and hundreds more.

### What it does

- **Any SE site** — set `site` to scrape Stack Overflow or any Stack Exchange community.
- **Search or browse** — free-text `query`, tag filters, and sort by votes / activity / newest / relevance.
- **Q\&A pairs** — enable `includeAnswers` to attach each question's answers (with accepted-answer flag) — ideal for fine-tuning and RAG.
- **Clean text** — question and answer bodies are converted from HTML to plain text.
- **Official API** — reliable, respectful, and rate-limit-aware (optional Stack Apps key raises the daily quota).

### Use cases

- Build **LLM/RAG datasets** of high-quality technical Q\&A.
- **Developer research** — find top questions/answers for a tag or topic.
- **Trend analysis** — track what a community is asking over time.
- **Content & docs** — surface common problems and canonical solutions.

### Input

| Field | Description |
|---|---|
| `site` | Stack Exchange site slug (default `stackoverflow`). |
| `query` | Free-text search (empty = top/newest questions). |
| `tags` | Only questions tagged with ALL of these. |
| `sort` | `votes`, `activity`, `creation`, or `relevance` (search only). |
| `includeAnswers` | Also fetch each question's answers (Q\&A pairs). |
| `maxItems` | Cap on questions returned (main cost lever). |
| `apiKey` | Optional Stack Apps key — raises daily quota 300 → 10,000. |

### Output

Each question becomes one dataset item:

```json
{
  "site": "stackoverflow",
  "questionId": 231767,
  "title": "What does the \"yield\" keyword do in Python?",
  "body": "What functionality does the yield keyword provide? ...",
  "tags": ["python", "iterator", "generator", "yield"],
  "score": 13135,
  "viewCount": 3200000,
  "answerCount": 51,
  "isAnswered": true,
  "acceptedAnswerId": 231855,
  "link": "https://stackoverflow.com/questions/231767/...",
  "author": "Alex. S.",
  "creationDate": "2008-10-23T22:21:11Z",
  "answers": [
    { "answerId": 231855, "score": 18315, "isAccepted": true,
      "body": "To understand what yield does, you must understand generators...",
      "author": "Sean Vieira", "creationDate": "2008-10-23T22:48:44Z" }
  ]
}
```

`answers` is present only when `includeAnswers` is on.

### Pricing

Pay-per-result: you're charged **per question returned** (answers are included in the question record).

### Notes

- Uses the **official Stack Exchange API v2.3**. Keyless runs share a 300 requests/day quota; add a free **Stack Apps `apiKey`** to raise it to 10,000/day for large jobs.
- Respects the API's `backoff` throttling automatically.

### FAQ

**Which sites work?** Any Stack Exchange site — just set its slug (e.g. `math.stackexchange`).

**Can I get answers, not just questions?** Yes — enable `includeAnswers`.

**What formats can I export?** JSON, JSONL, CSV, or Excel, or via the Apify API.

# Actor input Schema

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

Stack Exchange site slug, e.g. stackoverflow, superuser, serverfault, askubuntu, math.stackexchange, datascience.

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

Free-text search over question titles/bodies. Leave empty to get the newest/top questions.

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

Only questions tagged with ALL of these (e.g. python, pandas).

## `sort` (type: `string`):

Order of returned questions. 'Relevance' only applies when a search query is set.

## `includeAnswers` (type: `boolean`):

Also fetch each question's answers (Q\&A pairs — great for LLM datasets).

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

Cap on questions returned (main cost lever).

## `apiKey` (type: `string`):

Optional Stack Apps key to raise the daily quota from 300 to 10,000 requests. Leave empty to use the keyless quota.

## Actor input object example

```json
{
  "site": "stackoverflow",
  "tags": [],
  "sort": "votes",
  "includeAnswers": false,
  "maxItems": 100
}
```

# Actor output Schema

## `questions` (type: `string`):

One normalized question per item (with answers if enabled). Export as JSON, JSONL, CSV, or Excel.

# 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 = {};

// Run the Actor and wait for it to finish
const run = await client.actor("f0rty7even/stackexchange-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 = {}

# Run the Actor and wait for it to finish
run = client.actor("f0rty7even/stackexchange-scraper").call(run_input=run_input)

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

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

```

## CLI example

```bash
echo '{}' |
apify call f0rty7even/stackexchange-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=f0rty7even/stackexchange-scraper",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/acts/4eh96EriAeJvi4WTG/builds/auEXtK9Us0c45Vsj5/openapi.json
