# MLB Player Stats Scraper (MLB Stats API) (`devilscrapes/mlb-player-stats-scraper`) Actor

MLB player stats scraper on the official MLB stats API: season hitting, pitching and fielding stats per player (AVG, HR, RBI, OPS, ERA, WHIP, strikeouts) with team, league and position, ranked, as clean data.

- **URL**: https://apify.com/devilscrapes/mlb-player-stats-scraper.md
- **Developed by:** [DevilScrapes](https://apify.com/devilscrapes) (community)
- **Categories:** Other
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per event

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

<p align="center">
  <img src=".actor/icon.svg" width="160" alt="Devil Scrapes mark" />
</p>

## MLB Player Stats Scraper

**💰 $1.70 / 1 000 results**  ·  pay only for results  ·  no credit card to try

*The devil's in the data.* 😈

MLB player stats scraper for the official MLB stats API. Pick the seasons
and stat groups you want and get one clean row per player: hitting,
pitching or fielding season stats, ranked, with team, league and
position attached. Export to JSON, CSV or Excel, or pull it straight from
the Apify API.

### 🎯 What this scrapes

The MLB stats API serves season leaderboards fifty players at a time, one
stat group at a time. This Actor walks every page of every season and
group you ask for and returns one row per player season line, with the
stat block flattened into typed columns instead of nested JSON.

- **Hitting:** games, plate appearances, at bats, runs, hits, doubles,
  triples, home runs, RBI, walks, strikeouts, stolen bases, AVG, OBP, SLG,
  OPS, BABIP, total bases and more.
- **Pitching:** wins, losses, saves, holds, ERA, WHIP, innings pitched,
  strikeouts, walks, K/9, BB/9, HR/9, batters faced, pitch counts and more.
- **Fielding:** games, assists, put outs, errors, chances, double plays,
  fielding percentage, range factor, innings.
- **Identity on every row:** season, group, leaderboard rank, player id and
  name, team, league (AL / NL), position and the player pool applied.

### 🔥 Features

- 🛡️ **We rotate browser fingerprints** (curl-cffi Chrome, Firefox and
  Safari impersonation) so the source sees a real browser's TLS handshake,
  not a Python script.
- 🔁 **We retry with exponential backoff** on rate limits and server
  errors, honouring `Retry-After`. Up to 5 attempts per page.
- 🌐 **We rotate proxy sessions** through Apify Proxy on every retry,
  with a fresh session and exit IP each time.
- 🧊 **Typed, deduplicated rows.** Counts are integers, rates such as
  AVG and ERA are numbers, and the same player line never appears twice in
  your dataset.
- 🧱 **Fault isolation.** One season or group that fails does not end the
  others; we log it and keep going.
- 💰 **You pay only for results that land.** No data, no charge (only the
  small `actor-start` warm-up fee).

### 💡 Use cases

- **Fantasy and DFS tools:** refresh season hitting and pitching lines
  for projections and waiver-wire dashboards.
- **Sports betting and analytics teams:** build player-level models from
  ranked MLB season stats across several years.
- **Journalists and bloggers:** pull leaderboards for a season in one run
  instead of copying tables by hand.
- **Data science and teaching:** a clean, typed baseball dataset for
  notebooks, courses and BI dashboards.

### ⚙️ How to use it

1. Set `seasons` (for example `2025`) and the `groups` you want:
   `hitting`, `pitching`, `fielding`.
2. Leave `playerPool` on `QUALIFIED` for the qualified leaderboard, or
   switch to `ALL` to widen it.
3. Set `maxItems` to bound the run, then start it and export the dataset.

### 📥 Input

| Field | Type | Required | Default | Notes |
|---|---|---|---|---|
| `seasons` | `array<string>` | no | current year | Four-digit seasons, e.g. `2025`. |
| `groups` | `array<string>` | no | `hitting` | `hitting`, `pitching`, `fielding`, paged in the order given. |
| `playerPool` | `string` | no | `QUALIFIED` | `QUALIFIED` leaderboard, or `ALL` players. |
| `sportId` | `integer` | no | `1` | MLB sport id (`1` = Major League Baseball). |
| `maxItems` | `integer` | no | `100` | Hard cap on total rows across the run (1-50000). |
| `proxyConfiguration` | `object` | no | Apify Proxy | Apify Proxy configuration. |

#### Example input

```json
{
  "seasons": ["2025"],
  "groups": ["pitching", "hitting"],
  "playerPool": "QUALIFIED",
  "sportId": 1,
  "maxItems": 100,
  "proxyConfiguration": { "useApifyProxy": true }
}
```

### 📤 Output

One row per player season line in a group. Fields that do not apply to a
group are `null`. In the pitching group, shared fields such as `hits`,
`homeRuns` and `strikeOuts` are the pitcher's totals allowed or recorded;
use the `group` column to tell the groups apart.

| Field | Type | Notes |
|---|---|---|
| `season` | `integer` | Season year. |
| `group` | `string` | `hitting`, `pitching` or `fielding`. |
| `rank` | `integer \| null` | Leaderboard rank in the group and pool. |
| `playerId` / `playerName` | `integer` / `string` | MLB person id and full name. |
| `teamId` / `teamName` | `integer \| null` / `string \| null` | Team. |
| `leagueId` / `league` | `integer \| null` / `string \| null` | League (AL / NL). |
| `positionCode` / `positionAbbr` / `positionName` | `string \| null` | Position. |
| `numTeams` | `integer \| null` | Teams the player appeared for that season. |
| `gamesPlayed`, `atBats`, `hits`, `homeRuns`, `rbi`, ... | `integer \| null` | Count stats. |
| `avg`, `obp`, `slg`, `ops`, `era`, `whip`, ... | `number \| null` | Rate stats as numbers. |
| `inningsPitched`, `innings` | `string \| null` | Baseball notation: `187.2` is 187 and 2/3 innings. |
| `playerPool` / `sportId` | `string` / `integer` | What the feed applied. |
| `scrapedAt` | `string` | UTC ISO-8601 run timestamp. |

The full column list is in the dataset schema (about 95 fields).

#### Example output record

```json
{
  "season": 2025,
  "group": "hitting",
  "rank": 1,
  "playerId": 592450,
  "playerName": "Aaron Judge",
  "teamId": 147,
  "teamName": "New York Yankees",
  "leagueId": 103,
  "league": "AL",
  "positionAbbr": "RF",
  "gamesPlayed": 152,
  "atBats": 541,
  "hits": 179,
  "homeRuns": 53,
  "rbi": 114,
  "avg": 0.331,
  "obp": 0.457,
  "slg": 0.688,
  "ops": 1.145,
  "playerPool": "QUALIFIED",
  "scrapedAt": "2026-10-12T08:00:00Z"
}
```

### 💰 Pricing

Pay-Per-Event: you pay only when these events fire.

| Event | USD | What it is |
|---|---:|---|
| `actor-start` | $0.20 | One-off warm-up charge per run |
| `result-emitted` | $0.0015 | Per player season line written to the dataset |

Example: 1 000 rows = **$1.70 per run** ($0.20 start + 1000 x $0.0015).
No subscription, no minimum, no card required to try it.

### 🚧 Limitations

- **Season stats only.** This returns season leaderboards by group.
  Game logs, schedules, rosters and play-by-play are out of scope.
- **Qualified by default.** `QUALIFIED` returns the qualified leaderboard
  (for 2025: 145 hitters, 52 pitchers); switch `playerPool` to `ALL` for
  everyone with a stat line.
- **Traded players.** A player who appeared for several teams can show up
  on more than one row; check `numTeams` and `teamName`.
- **Stat names follow the feed.** Fields keep the MLB stats API's own
  names, and a field that does not apply to a group is `null`.
- **A season with no data is a success.** It finishes with zero rows and
  a status message naming what was requested.

### ❓ FAQ

**Do I need an MLB API key?**
No. This reads the official MLB stats API; there is nothing to sign up for.

**How do I get both hitting and pitching?**
Put both in `groups`. Each group is paged separately and every row carries
its `group`.

**Why did my run return fewer rows than `maxItems`?**
Either the leaderboard has fewer players than your cap, or you asked for a
single season and group. The status message tells you why each group
stopped.

**Can I pull several seasons at once?**
Yes. Pass several years to `seasons`; each season and group is paged in
turn and every row carries its `season`.

**What happens if a page is blocked or fails?**
We retry up to 5 times with a fresh browser fingerprint and proxy session
each time. If a season and group still cannot be read, the others carry on
and the status message says so. The run ends as failed only when a page
was unreadable and nothing at all could be collected.

**Can I run this on a schedule?**
Yes. Use Apify Schedules to refresh the leaderboard daily during the
season.

### 💬 Your feedback

Found a bug, or need a field we don't return yet? Open an issue on the
Actor's Issues tab. We read every one.

# Changelog

This Actor's version history is a separate document: https://apify.com/devilscrapes/mlb-player-stats-scraper/changelog.md

# Actor input Schema

## `seasons` (type: `array`):

Seasons to pull, as four-digit years (for example 2025). Leave empty for the current season.

## `groups` (type: `array`):

Which stat groups to pull: hitting, pitching, fielding. Each group is paged separately, in the order given.

## `playerPool` (type: `string`):

QUALIFIED returns the qualified leaderboard; ALL widens it to every player with a stat line.

## `sportId` (type: `integer`):

MLB sport id. 1 is Major League Baseball.

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

Hard cap on total rows emitted across the whole run (50 rows per page).

## `proxyConfiguration` (type: `object`):

Apify Proxy configuration. The default datacenter proxy is enough for this source.

## Actor input object example

```json
{
  "seasons": [
    "2025"
  ],
  "groups": [
    "pitching",
    "hitting"
  ],
  "playerPool": "QUALIFIED",
  "sportId": 1,
  "maxItems": 100,
  "proxyConfiguration": {
    "useApifyProxy": true
  }
}
```

# Actor output Schema

## `datasetItems` (type: `string`):

All dataset items as JSON.

## `datasetItemsCsv` (type: `string`):

Same data exported to CSV.

## `datasetView` (type: `string`):

Open the run dataset in the Console.

# 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 = {
    "seasons": [
        "2025"
    ],
    "groups": [
        "pitching",
        "hitting"
    ],
    "playerPool": "QUALIFIED",
    "sportId": 1,
    "maxItems": 100,
    "proxyConfiguration": {
        "useApifyProxy": true
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("devilscrapes/mlb-player-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 = {
    "seasons": ["2025"],
    "groups": [
        "pitching",
        "hitting",
    ],
    "playerPool": "QUALIFIED",
    "sportId": 1,
    "maxItems": 100,
    "proxyConfiguration": { "useApifyProxy": True },
}

# Run the Actor and wait for it to finish
run = client.actor("devilscrapes/mlb-player-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 '{
  "seasons": [
    "2025"
  ],
  "groups": [
    "pitching",
    "hitting"
  ],
  "playerPool": "QUALIFIED",
  "sportId": 1,
  "maxItems": 100,
  "proxyConfiguration": {
    "useApifyProxy": true
  }
}' |
apify call devilscrapes/mlb-player-stats-scraper --silent --output-dataset

```

## MCP server setup

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