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

Scrape MLB teams, rosters, schedules, standings, player stats, and game details from MLB's official Stats API. Get team info, player bios, box scores, and hitting/pitching/fielding stats by season.

- **URL**: https://apify.com/parsebird/mlb-stats-scraper.md
- **Developed by:** [ParseBird](https://apify.com/parsebird) (community)
- **Categories:** News, Automation, Travel
- **Stats:** 3 total users, 2 monthly users, 100.0% runs succeeded, 1 bookmarks
- **User rating**: No ratings yet

## Pricing

from $2.89 / 1,000 record scrapeds

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

### MLB Stats Scraper

Scrape [MLB's official Stats API](https://www.mlb.com/) for teams, rosters, schedules, standings, player stats, and full game details — clean, structured baseball data by season instead of manually browsing MLB.com.

<table><tr>
<td style="border-left:4px solid #1C1917;padding:12px 16px;font-weight:600">
Six modes covering every major MLB dataset — teams, rosters, schedules, standings, hitting/pitching/fielding stats, and box scores — all sourced directly from MLB's own Stats API.
</td>
</tr></table>

##### Copy to your AI assistant

Copy this block into ChatGPT, Claude, Cursor, or any LLM to start using this actor.

```
parsebird/mlb-stats-scraper on Apify. Call: ApifyClient("TOKEN").actor("parsebird/mlb-stats-scraper").call(run_input={...}), then client.dataset(run["defaultDatasetId"]).list_items().items for results. Key inputs: mode (string, "teams"/"players"/"schedule"/"standings"/"playerStats"/"gameDetails", default "teams"), season (integer, default current year), teamId (integer, e.g. 147=Yankees, 111=Red Sox — used by players/schedule), playerId (integer, e.g. 660271=Shohei Ohtani — required for playerStats, used by players), gamePk (integer, required for gameDetails), date (string "YYYY-MM-DD", schedule mode), fromDate/toDate (string, schedule date range), leagueId ("both"/"AL"/"NL", standings mode), statGroup ("hitting"/"pitching"/"fielding", playerStats mode), gameType ("R"/"S"/"P"/"W"/etc, schedule mode), maxItems (integer, default 100, max 10000). Output fields vary by mode: teams give teamId/name/abbreviation/leagueName/divisionName/venueName/mlbUrl; players give playerId/fullName/birthDate/height/weight/primaryPosition/currentTeam/batSide/pitchHand/mlbUrl; schedule gives gamePk/gameDate/homeTeam/awayTeam/homeScore/awayScore/status/venue; standings give teamName/divisionName/wins/losses/pct/divisionRank/gamesBack/streakCode; playerStats give gamesPlayed/homeRuns/rbi/avg/obp/slg/ops/era/whip/wins. Full actor spec: fetch build via GET https://api.apify.com/v2/acts/parsebird~mlb-stats-scraper (Bearer TOKEN). Get token: https://console.apify.com/account/integrations
```

### What does MLB Stats Scraper do?

This Actor scrapes [MLB's official Stats API](https://www.mlb.com/), the same data source that powers MLB.com's own scoreboards and stat pages, and normalizes it into clean, structured records.

- ⚾ **Six modes** — teams, player rosters/bios, schedules, standings, hitting/pitching/fielding stats, and full game box scores
- 📅 **Flexible date filtering** — a single date or a date range for schedules, any season year for stats and standings
- 🏆 **League and division context** — standings include division rank, games back, and streak; teams include league and division name
- 📊 **All three stat groups** — hitting, pitching, and fielding stats for any player and season
- ⏱️ **Scheduling** — run this Actor daily during the season to track standings movement or pull the day's schedule
- 🔌 **API access** — trigger runs and pull results programmatically via the Apify API or client libraries
- 📊 **Flexible export** — download results as JSON, CSV, or Excel, or query them via API

### What data can you extract from MLB Stats?

| Field | Description |
|-------|-------------|
| `teamId` / `name` / `abbreviation` | Team identity (teams mode) |
| `leagueName` / `divisionName` / `venueName` | Team's league, division, and home stadium |
| `playerId` / `fullName` / `birthDate` / `height` / `weight` | Player bio (players mode) |
| `primaryPosition` / `currentTeam` / `batSide` / `pitchHand` | Player role and handedness |
| `gamePk` / `gameDate` / `homeTeam` / `awayTeam` / `homeScore` / `awayScore` | Game identity and result (schedule/gameDetails) |
| `wins` / `losses` / `pct` / `divisionRank` / `gamesBack` / `streakCode` | Standings (standings mode) |
| `homeRuns` / `rbi` / `avg` / `obp` / `slg` / `ops` / `era` / `whip` | Hitting/pitching stats (playerStats mode) |

### Input parameters

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `mode` | string | **Yes** | `teams` | `teams`, `players`, `schedule`, `standings`, `playerStats`, or `gameDetails` |
| `season` | integer | No | current year | MLB season year |
| `teamId` | integer | No | — | MLB team ID, e.g. `147` = Yankees, `111` = Red Sox |
| `playerId` | integer | No | — | MLB player ID, e.g. `660271` = Shohei Ohtani. Required for `playerStats` |
| `gamePk` | integer | No | — | Game primary key. Required for `gameDetails` |
| `date` | string | No | — | Game date `YYYY-MM-DD` (schedule mode) |
| `fromDate` | string | No | — | Start date for a schedule date range |
| `toDate` | string | No | — | End date for a schedule date range |
| `leagueId` | string | No | `both` | `both`, `AL`, or `NL` (standings mode) |
| `statGroup` | string | No | `hitting` | `hitting`, `pitching`, or `fielding` (playerStats mode) |
| `gameType` | string | No | all types | `R` (regular), `S` (spring), `P` (playoffs), `W` (World Series), and other MLB game-type codes |
| `maxItems` | integer | No | `100` | Maximum records to return (1–10,000) |

### Output example

```json
{
  "gamePk": 744834,
  "gameDate": "2024-07-04T15:05:00Z",
  "homeTeam": "Washington Nationals",
  "awayTeam": "New York Mets",
  "homeScore": 1,
  "awayScore": 0,
  "status": "Final",
  "venue": "Nationals Park"
}
```

```json
{
  "playerId": 660271,
  "season": 2024,
  "gamesPlayed": 159,
  "homeRuns": 54,
  "rbi": 130,
  "avg": ".310",
  "obp": ".390",
  "slg": ".646",
  "ops": "1.036",
  "era": null,
  "whip": null,
  "wins": null
}
```

Download results in **JSON, CSV, or Excel** directly from the Apify Console, or pull them programmatically via the API.

### Use cases

- **Fantasy baseball research** — pull hitting/pitching stats for any player and season to compare performance
- **Standings tracking** — schedule a daily run against `standings` mode to track division races over a season
- **Schedule aggregation** — pull a team's or a whole day's schedule and feed it into your own calendar or app
- **Historical analysis** — pull team, player, and game data for any past season for research or modeling
- **Game recaps** — pull `gameDetails` for a specific `gamePk` to get box score stats and inning-by-inning line scores

### How to scrape MLB stats with this Actor

1. Go to the [MLB Stats Scraper](https://apify.com/parsebird/mlb-stats-scraper) page on Apify Store
2. Click **Try for free** — new users get a free trial to test the Actor before paying
3. Choose a **mode** and fill in the fields it needs (e.g. `teamId` for a roster, `playerId` + `season` for stats)
4. Set `maxItems` to cap the run size
5. Click **Start** — the Actor queries MLB's Stats API and normalizes every result
6. When the run finishes, download your data as **JSON, CSV, or Excel**, or fetch it via the API

### Use with the Apify API

**Python**

```python
from apify_client import ApifyClient

client = ApifyClient("YOUR_API_TOKEN")

run = client.actor("parsebird/mlb-stats-scraper").call(run_input={
    "mode": "playerStats",
    "playerId": 660271,
    "season": 2024,
    "statGroup": "hitting",
})

for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(f"{item['homeRuns']} HR, {item['rbi']} RBI, {item['avg']} AVG")
```

**JavaScript**

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

const client = new ApifyClient({ token: 'YOUR_API_TOKEN' });

const run = await client.actor('parsebird/mlb-stats-scraper').call({
    mode: 'playerStats',
    playerId: 660271,
    season: 2024,
    statGroup: 'hitting',
});

const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.log(`${item.homeRuns} HR, ${item.rbi} RBI, ${item.avg} AVG`);
});
```

See the [Apify API documentation](https://docs.apify.com/api/v2) for full reference, or the Actor's **API** tab for ready-to-run request snippets in more languages.

### How much does it cost to scrape MLB stats?

This Actor uses **Pay-per-event** pricing — you only pay for records actually returned, with no separate platform rental fee.

| Plan | Price per event | Price per 1,000 |
|------|-----------------|-----------------|
| Free | $0.00459 | $4.59 |
| Bronze | $0.00419 | $4.19 |
| Silver | $0.00349 | $3.49 |
| Gold | $0.00289 | $2.89 |

One `record-scraped` event is charged for each team, player, game, standing, or stat line pushed to the dataset. A 1,000-record run costs about $4.59 on the Free plan or $2.89 on Gold. Start with the free trial and a low `maxItems` to preview results before scaling up.

### FAQ

**What team IDs should I use?**
Common ones: `147` = Yankees, `111` = Red Sox, `112` = Cubs, `117` = Astros, `108` = Angels, `121` = Mets, `119` = Dodgers, `137` = Giants, `144` = Braves, `143` = Phillies. Run `mode: "teams"` to get the full list of all 30 team IDs.

**Why is `currentTeam` sometimes different from the team I searched under?**
`currentTeam` reflects the player's team as of right now, not necessarily the team for the `season` you requested — a player fetched under a 2024 roster may since have been traded, released, or moved organizations. This is MLB's own data, not a bug.

**Why are `era`/`whip`/`wins` (or `homeRuns`/`avg`) null in my `playerStats` result?**
Those fields only populate for the matching `statGroup` — hitting stats return null pitching fields and vice versa, rather than a fabricated zero.

**What's the difference between `schedule` and `gameDetails`?**
`schedule` returns lightweight game summaries (score, status, teams) for a date or date range. `gameDetails` requires a specific `gamePk` and returns the full box score: inning-by-inning line score and team batting/pitching/fielding stat totals.

**Can I schedule recurring runs?**
Yes. Use Apify's [Scheduler](https://docs.apify.com/platform/schedules) to run this Actor daily during the season to track standings or pull each day's schedule automatically.

**Is it legal to scrape MLB's Stats API?**
This data comes from MLB's own publicly accessible Stats API, the same one that powers MLB.com's scoreboards. You're responsible for complying with MLB Advanced Media's terms for your specific use case. See Apify's [blog post on the legality of web scraping](https://blog.apify.com/is-web-scraping-legal/) for general background.

**Can I access results via API?**
Yes. Every run's dataset is available through the [Apify API](https://docs.apify.com/api/v2) and client libraries (Python, JavaScript) — see the Actor's **API** tab for ready-made snippets.

**Something not working?**
Open an issue on the Actor's **Issues** tab in Apify Console — the ParseBird team monitors it directly.

### Related Actors

Other sports and market-data Actors from ParseBird:

- [Tennis Abstract Player Match Scraper & API](https://apify.com/parsebird/tennis-abstract-match-scraper) — historical tennis match data by player
- [Polymarket Leaderboard Scraper](https://apify.com/parsebird/polymarket-scraper) — prediction-market leaderboard and odds data
- [Polymarket Market Scraper](https://apify.com/parsebird/polymarket-market-scraper) — prediction-market pricing and market data

# Actor input Schema

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

What to scrape.

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

MLB season year. Defaults to the current year.

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

MLB team ID, e.g. 147 = Yankees, 111 = Red Sox. Used by 'players' (roster) and optionally 'schedule' (filter to one team's games).

## `playerId` (type: `integer`):

MLB player ID, e.g. 660271 = Shohei Ohtani. Required for 'playerStats'; used by 'players' when no teamId is given.

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

Game primary key. Required for mode=gameDetails.

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

Game date as YYYY-MM-DD. Used by 'schedule' for a single day.

## `fromDate` (type: `string`):

Start date (YYYY-MM-DD) for a schedule date range. Used instead of 'date'.

## `toDate` (type: `string`):

End date (YYYY-MM-DD) for a schedule date range.

## `leagueId` (type: `string`):

Restrict standings to one league. Used by 'standings'.

## `statGroup` (type: `string`):

Type of stats to return. Used by 'playerStats'.

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

Restrict schedule results to one game type.

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

Maximum records to return.

## Actor input object example

```json
{
  "mode": "teams",
  "season": 2024,
  "teamId": 147,
  "playerId": 660271,
  "gamePk": 744834,
  "date": "2024-07-04",
  "leagueId": "both",
  "statGroup": "hitting",
  "gameType": "R",
  "maxItems": 30
}
```

# Actor output Schema

## `dataset` (type: `string`):

No description

# 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": "teams",
    "season": 2024,
    "teamId": 147,
    "playerId": 660271,
    "gamePk": 744834,
    "date": "2024-07-04",
    "fromDate": "",
    "toDate": "",
    "leagueId": "both",
    "statGroup": "hitting",
    "gameType": "R",
    "maxItems": 30
};

// Run the Actor and wait for it to finish
const run = await client.actor("parsebird/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": "teams",
    "season": 2024,
    "teamId": 147,
    "playerId": 660271,
    "gamePk": 744834,
    "date": "2024-07-04",
    "fromDate": "",
    "toDate": "",
    "leagueId": "both",
    "statGroup": "hitting",
    "gameType": "R",
    "maxItems": 30,
}

# Run the Actor and wait for it to finish
run = client.actor("parsebird/mlb-stats-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 '{
  "mode": "teams",
  "season": 2024,
  "teamId": 147,
  "playerId": 660271,
  "gamePk": 744834,
  "date": "2024-07-04",
  "fromDate": "",
  "toDate": "",
  "leagueId": "both",
  "statGroup": "hitting",
  "gameType": "R",
  "maxItems": 30
}' |
apify call parsebird/mlb-stats-scraper --silent --output-dataset

```

## MCP server setup

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

```

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/86TKq2cNZgJKcdzcv/builds/e4WqQkgE6Th7MdeCe/openapi.json
