# 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
- **Features:** Limited permissions
- **Stats:** 3 total users, 2 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/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

## 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(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 '{}' |
apify call f0rty7even/stackexchange-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,f0rty7even/stackexchange-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/4eh96EriAeJvi4WTG/builds/auEXtK9Us0c45Vsj5/openapi.json
