# MLB Stats Scraper (`parseforge/mlb-stats-scraper`) Actor

Scrapes official MLB stats by mode: schedule, teams, roster, player stats, or live game detail. Returns each record as a flat row ready for CSV, JSON, Excel, or XML export.

- **URL**: https://apify.com/parseforge/mlb-stats-scraper.md
- **Developed by:** [ParseForge](https://apify.com/parseforge) (community)
- **Categories:** News, Business, Automation
- **Stats:** 191 total users, 51 monthly users, 100.0% runs succeeded, 1 bookmarks
- **User rating**: No ratings yet

## Pricing

from $25.50 / 1,000 results

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?

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

[![ParseForge](https://raw.githubusercontent.com/ParseForge/apify-assets/main/banner.jpg)](https://apify.com/parseforge?fpr=vmoqkp)

### MLB Stats Scraper

**Scrape official MLB stats for any player, team, roster, schedule, or live game detail.** Pull season stats, game feeds, and team data straight from the MLB Stats API. Export to CSV, JSON, Excel, or XML.

The MLB Stats API is the official data feed behind every box score, but pulling it into a flat dataset means handling nested endpoints, pagination, and date logic. This Actor wraps the feed so you request a mode (schedule, teams, roster, player stats, or live game detail), set a few filters, and get back clean rows. No API key, no hand-rolled client.

| Who uses it | What they scrape MLB Stats API for |
|---|---|
| Sports analysts | Pull season-long player stats to build performance models. |
| Fantasy baseball players | Grab daily schedules and rosters to set lineups. |
| Sportsbook operators | Fetch live game details to feed real-time betting markets. |
| Data journalists | Collect historical schedules and team data for season previews. |

### What it does

This Actor collects MLB data by mode (schedule, teams, roster, player stats, or game detail) and returns each record as a flat row.

- 📅 **Schedule mode:** pull games by date, season, and game type (regular, postseason, or All-Star).
- 🧢 **Teams mode:** get the full list of active MLB teams with their IDs and league info.
- 👥 **Roster mode:** fetch a team's current roster, or batch up to 100 team IDs in one run.
- 📊 **Player Stats mode:** request season stats for a single player, or batch up to 100 player IDs.
- ⚾ **Game Detail mode:** get the live feed for a specific game by its MLB game PK.

Results export to CSV, JSON, Excel, or XML, or straight from the API.

### What you can do with MLB Stats API data

**📈 Build a player performance dashboard.**

A fantasy analyst runs playerStats mode with a batch of player IDs each morning and feeds the CSV into a Google Sheet that tracks rolling averages.

**📅 Monitor today's matchups.**

A sportsbook operator runs schedule mode with today's date and the regular season filter to populate a daily odds board.

**🧢 Audit team rosters weekly.**

A data journalist runs roster mode for all 30 teams every Monday to track call-ups and injuries for a weekly column.

**⚾ Power a live score widget.**

A developer runs gameDetail mode for an active game PK every 60 seconds and pushes the live feed to a website widget.

### Why choose this scraper

|  | What you get |
|---|---|
| **Official data source** | Reads directly from the MLB Stats API, the same feed that powers MLB.com. |
| **Five modes, one actor** | Schedule, teams, roster, player stats, and live game detail in a single tool. |
| **Batch lookups** | Send up to 100 team IDs or player IDs per run for roster and stats modes. |
| **Flat output** | Nested API responses are flattened into rows ready for CSV, JSON, Excel, or XML. |

### How it compares

No other Store actor targets MLB Stats API the same way, so the honest comparison is with the alternatives teams actually weigh.

| | MLB Stats Scraper | Build it in-house | By hand |
|---|---|---|---|
| Setup | Run it now, zero config | Days of engineering | None, but hours per pull |
| When MLB Stats API changes | Maintained for you | You fix it | You re-learn the page |
| Proxies, retries, anti-bot | Built in | Your problem | Browser only |
| Output | Fixed JSON schema, CSV/Excel export | Whatever you build | Copy-paste |
| Cost | Pay per result | Engineering time | Analyst hours |

### Configure the run

Drive the Actor by picking a mode, then supply a date, team ID, player ID, game PK, or season year. Filters run as each request is made so only matching records reach your dataset. The Input tab lists every parameter.

A first run with the defaults:

```json
{
  "mode": "schedule",
  "maxItems": 10
}
```

A larger pull:

```json
{
  "mode": "schedule",
  "maxItems": 200
}
```

### Pricing

Pay-per-result: **$0.034 per result** collected. You pay only for the results written to your dataset.

| Results collected | Approximate cost |
|---|---|
| 100 results | $3.40 |
| 1,000 results | $34.00 |
| 10,000 results | $340.00 |

New Apify accounts start with $5 in free credit.

### Free users

Free-plan runs return up to 10 results as a preview. [Upgrade your Apify plan](https://console.apify.com/sign-up?fpr=vmoqkp) to collect up to 1,000,000 results per run.

### Run it

1. [Create a free Apify account with $5 in credit](https://console.apify.com/sign-up?fpr=vmoqkp).
2. Open the [MLB Stats Scraper](https://apify.com/parseforge/mlb-stats-scraper?fpr=vmoqkp).
3. Set your inputs and any filters, then click **Start**.
4. Export the results as CSV, Excel, JSON, or XML from the **Dataset** tab.

Run it programmatically through the [Apify API](https://docs.apify.com/api/v2) (`run-sync-get-dataset-items`) or the [ApifyClient](https://docs.apify.com/api/client/js) for JavaScript and Python.

### Use with AI agents (MCP)

Give an AI agent live access to MLB Stats API through the Model Context Protocol. Add the Actor to Claude, Cursor, or any MCP client:

```bash
claude mcp add --transport http apify "https://mcp.apify.com/?tools=parseforge/mlb-stats-scraper"
```

Then prompt it in plain language to run the scraper and read back the results.

### Troubleshooting

**Why am I getting no results from schedule mode?**

Check that the date you supplied has games. If you left the date blank, it defaults to today. During the offseason or on off-days, there may be no games scheduled. Try a date during the regular season.

**Why does my player ID return an error?**

Make sure the player ID is correct. Run roster mode for the player's team to verify the ID. Also confirm the player is on an active roster or has stats for the season you requested.

**Why is my batch lookup slow?**

Batch lookups for up to 100 team IDs or player IDs make one API call per ID. Set maxItems to a reasonable number and expect longer runs for large batches.

**Why am I getting a 404 for a game PK?**

The game PK may be for a future game that does not have a live feed yet, or a past game outside the accessible range. Verify the game PK by running schedule mode for the game's date.

**Why does my CSV have nested fields?**

Some MLB API responses contain deeply nested objects. The Actor flattens most fields, but very complex nested structures may appear as JSON strings in a cell. Use the JSON export format if you need to parse these programmatically.

### FAQ

| Question | Answer |
|---|---|
| Do I need an MLB API key to use this scraper? | No. This Actor reads from the public MLB Stats API endpoints. No registration or API key is required. |
| What is a game PK and where do I find it? | A game PK is MLB's unique identifier for a single game. You can find it by running schedule mode first. Each game in the schedule output includes its gamePk. |
| How do I find a team ID? | Run the Actor in teams mode to get the full list of MLB teams with their IDs. Common IDs include 147 for the Yankees and 119 for the Dodgers. |
| How do I find a player ID? | Run roster mode for a team to see its current players and their IDs. You can also look up a player on the MLB website. The numeric ID in the URL is their player ID. |
| Can I get stats for multiple players at once? | Yes. Use the playerIds array in playerStats mode to send up to 100 player IDs in a single run. |
| Can I get rosters for multiple teams at once? | Yes. Use the teamIds array in roster mode to send up to 100 team IDs in a single run. |
| What seasons does this cover? | The MLB Stats API includes historical data going back many years. Set the season field to any year from 1900 onward. |
| Can I filter the schedule by postseason games only? | Yes. Set seasonType to 'post' for a shortcut that includes Wild Card, Division Series, League Championship, and World Series games. Or set gameType to a specific round. |
| What does the live game detail feed include? | Game detail mode returns the full live feed: current score, inning, outs, runners on base, count on the batter, and play-by-play events. |
| How many records can I collect in one run? | You can set maxItems up to 1,000,000 records per run. The actual number depends on the mode and the date range or batch size you supply. |

### Related actors

Browse the full [ParseForge collection](https://apify.com/parseforge?fpr=vmoqkp) for more scrapers.

🆘 **Need help?** Email parseforge@protonmail.com with your run ID, your input, and what you expected.

⚠️ **Disclaimer.** This Actor is unofficial and is not affiliated with, endorsed by, or sponsored by MLB Advanced Media, L.P. It collects only publicly available data. You are responsible for using the collected data in compliance with the source's terms of service and applicable data-protection laws, including GDPR, CCPA, and PIPL. Do not use it to collect personal data unlawfully.

# Actor input Schema

## `mode` (type: `string`):

What to fetch from the official MLB Stats data feed. Default is 'schedule' (today's games when no date is supplied).

## `date` (type: `string`):

Date for schedule mode. Defaults to today.

## `teamId` (type: `integer`):

MLB team ID for roster mode (e.g. 147=Yankees, 119=Dodgers).

## `teamIds` (type: `array`):

Array of MLB team IDs for batch roster lookup. Takes precedence over single teamId. Items can be integers or numeric strings. Max 100 per call.

## `playerId` (type: `string`):

MLB player ID for playerStats mode (e.g. 660271 = Shohei Ohtani). Numeric, accepted as string so copy-pasted IDs work.

## `playerIds` (type: `array`):

Array of MLB player IDs for batch season-stats lookup. Takes precedence over single playerId. Max 100 per call.

## `gameType` (type: `string`):

Filter schedule by game type. R=Regular, F=Wild Card, D=Division Series, L=League Championship, W=World Series, A=All-Star.

## `seasonType` (type: `string`):

Convenience filter that maps to gameType: 'regular' = R, 'post' = F,D,L,W. Ignored if gameType is set.

## `gamePk` (type: `integer`):

Game primary key for gameDetail mode.

## `season` (type: `integer`):

Season year (e.g. 2024). Defaults to current year.

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

Maximum number of MLB stat records to collect per run.

## Actor input object example

```json
{
  "mode": "schedule",
  "teamIds": [],
  "playerIds": [],
  "gameType": "",
  "seasonType": "",
  "maxItems": 10
}
```

# Actor output Schema

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

Overview of scraped data

## `fullData` (type: `string`):

Complete dataset

# 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 = {
    "mode": "schedule",
    "date": "",
    "playerId": "",
    "maxItems": 10
};

// Run the Actor and wait for it to finish
const run = await client.actor("parseforge/mlb-stats-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 = {
    "mode": "schedule",
    "date": "",
    "playerId": "",
    "maxItems": 10,
}

# Run the Actor and wait for it to finish
run = client.actor("parseforge/mlb-stats-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 '{
  "mode": "schedule",
  "date": "",
  "playerId": "",
  "maxItems": 10
}' |
apify call parseforge/mlb-stats-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,parseforge/mlb-stats-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/AlkEp5UOnj5DxTJQh/builds/pBFk9MbYI1iktAze0/openapi.json
