# Mlb Stats Scraper (`real-estate-api/mlb-stats-scraper`) Actor

MLB Stats Scraper is a Python tool designed to extract real-time and historical Major League Baseball data, including player statistics, game box scores, team standings, and schedules. It exports structured baseball datasets into clean CSV or JSON formats for sports analytics and fantasy modeling.

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

## Pricing

from $2.99 / 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?

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

## MLB Stats Scraper: MLB Teams, Schedules, Rosters, and Players

<p align="center">
  <img src="https://imgur.com/Kip1MKj.png" alt="MLB Stats Scraper" width="800" />
</p>

### Overview

MLB Stats Scraper collects structured Major League Baseball information, including team profiles, single-day schedules, active rosters, and player biographies. Export available game details, scores, venues, team information, player positions, and other fields to JSON, CSV, or Excel.

The actor supports five modes: `schedule`, `team`, `teams`, `roster`, and `player`. Each mode collects a specific type of baseball information. Available fields may vary depending on the selected mode and the source data.

### Features

- Collect schedules for a selected date.
- Retrieve individual team details or multiple team records.
- Collect a team's active roster.
- Retrieve player information using player IDs.
- Extract game dates, status, scores, venues, and participating teams.
- Collect available player details, including positions, jersey numbers, and biographical information.
- Deduplicate records by ID within a run.
- Export structured datasets to JSON, CSV, or Excel.
- Schedule recurring runs through Apify.

### Use Cases

- **MLB schedule tracking:** Export games for a selected date, including teams, scores, venues, and game status.
- **Team research:** Collect team names, abbreviations, leagues, divisions, and home venues.
- **Roster exports:** Build structured lists of players, jersey numbers, and positions.
- **Player research:** Collect available player information, including names, birth dates, height, weight, and primary position.
- **Recurring data collection:** Schedule regular exports for spreadsheets and compatible workflows.
- **Historical recordkeeping:** Maintain JSON or CSV snapshots for analysis and comparison.

### Input Parameters

| Parameter | Type | Default | Description |
|---|---|---|---|
| `mode` | string | `schedule` | Collection mode: `schedule`, `team`, `teams`, `roster`, or `player`. |
| `date` | string | `2026-09-15` | Schedule date in `YYYY-MM-DD` format. |
| `teamId` | integer | `108` | Team ID used by team and roster modes. ID `108` represents the Los Angeles Angels. |
| `personIds` | array | `[]` | Player IDs to process in player mode. |
| `maxItems` | integer | `100` | Maximum number of successful records to save, from 1 to 1,000. |
| `timeoutSecs` | integer | `300` | Overall time limit in seconds. |
| `requestTimeoutSecs` | integer | `30` | Timeout for an individual request, in seconds. |

### Example Input

#### Get a Daily Schedule

```json
{
  "mode": "schedule",
  "date": "2026-09-15",
  "maxItems": 100,
  "timeoutSecs": 300,
  "requestTimeoutSecs": 30
}
```

#### Get a Team Roster

```json
{
  "mode": "roster",
  "teamId": 108,
  "maxItems": 100
}
```

#### Get Player Details

```json
{
  "mode": "player",
  "personIds": [660271],
  "maxItems": 100
}
```

#### Get Team Information

```json
{
  "mode": "team",
  "teamId": 108,
  "maxItems": 100
}
```

#### Get Multiple Teams

```json
{
  "mode": "teams",
  "maxItems": 100
}
```

### Extracted Data

Each successful record represents a team, game, roster entry, or player. Records may include identifiers, source references, and collection timestamps.

Available information depends on the selected mode:

- **Schedules:** Game identifiers, dates, status, participating teams, scores, venues, and game notes.
- **Teams:** Team names, abbreviations, league and division information, venue details, spring league information, and first year of play.
- **Rosters:** Player identifiers, names, jersey numbers, and positions.
- **Players:** Names, birth dates, height, weight, and primary position, when available.

Duplicate IDs are saved only once per run. Invalid inputs or unusable source responses may produce error records, and the actor continues where possible.

### Example Output

The following example illustrates a schedule record. Values represent an example record; source fields and available data may change.

```json
{
  "recordKind": "game",
  "id": 824466,
  "name": "Los Angeles Dodgers at Cincinnati Reds",
  "gamePk": 824466,
  "season": 2026,
  "officialDate": "2026-09-15",
  "gameDate": "2026-09-15T22:40:00Z",
  "gameState": "Final",
  "awayTeamName": "Los Angeles Dodgers",
  "homeTeamName": "Cincinnati Reds",
  "awayScore": 4,
  "homeScore": 0,
  "venue": {
    "id": 2602,
    "name": "Great American Ball Park"
  },
  "gameNote": "Roberto Clemente Day",
  "link": "SOURCE_RESOURCE_PATH",
  "scrapedAt": "COLLECTION_TIMESTAMP"
}
```

### Field Reference

The fields included in each record depend on the collection mode and the information available from the source.

| Field | Type | Description |
|---|---|---|
| `id` | integer | Team ID, game ID, or player ID, depending on the record. |
| `name` | string | Team name, game matchup, or player name. |
| `recordKind` | string | Record category: `team`, `game`, `roster`, or `player`. |
| `season` | integer | Season year, when available. |
| `gamePk` | integer | Game identifier. |
| `officialDate` | string | Official game date. |
| `gameDate` | string | Scheduled game timestamp. |
| `gameState` | string | Game status, such as `Final`. |
| `awayTeamName` | string | Away team name. |
| `homeTeamName` | string | Home team name. |
| `awayScore` | integer | Away team score, when available. |
| `homeScore` | integer | Home team score, when available. |
| `venue` | object | Ballpark or venue information, including available IDs and names. |
| `gameNote` | string | Game note or event description, when available. |
| `link` | string | Related resource path provided in the record. |
| `abbreviation` | string | Team abbreviation, such as `LAA`. |
| `league` | object | League information for a team. |
| `division` | object | Division information for a team. |
| `springLeague` | object | Spring league information, when available. |
| `firstYearOfPlay` | string | Team's first year of play, when available. |
| `personId` | integer | Player identifier, when present. |
| `jersey` | string or integer | Player's jersey number. |
| `position` | object | Player position details. |
| `birthDate` | string | Player's date of birth, when available. |
| `height` | string | Player height, when available. |
| `weight` | integer | Player weight, when available. |
| `primaryPosition` | object | Player's primary position, when available. |
| `scrapedAt` | string | UTC timestamp when the record was saved. |
| `error` | string | Error description, present on error records. |
| `input` | object | Input details associated with a failed operation. |

Not every field appears in every record. Fields may be absent when the selected mode or source data does not provide them.

### Collection and Rate Limits

- **Maximum records:** `maxItems` accepts values from 1 to 1,000.
- **Request pacing:** Collection runs at approximately two requests per second.
- **Retries:** Temporary rate limits, server errors, and request timeouts may trigger up to three additional attempts, with delays of 2, 4, and 8 seconds. Longer server-specified retry delays are respected.
- **Schedule coverage:** Schedule mode collects games for one date per run. Collecting multiple dates requires separate runs.
- **Player collection:** Player mode can process multiple player IDs, subject to the configured record limit and request pacing.
- **Timeouts:** The actor uses an overall time limit and an individual request timeout.
- **Deduplication:** Duplicate IDs are skipped within a run.
- **Error handling:** Invalid inputs and unusable responses are recorded as error rows where possible. The actor continues processing when it can.
- **Source changes:** Source data structures and field availability may change over time.

### Attribution and Source Restrictions

Responses may include copyright notices attributed to MLB Advanced Media. MLB content may be subject to copyright and other restrictions, including limitations on commercial use.

Review the applicable source terms before using, publishing, or redistributing collected data. Preserve required attribution and respect applicable restrictions.

### FAQ

#### What collection modes are supported?

The actor supports `schedule`, `team`, `teams`, `roster`, and `player` modes.

#### Can I collect an entire season in one run?

Schedule mode is configured for one date per run. To collect multiple days, schedule separate runs for the dates you need.

#### What happens if a team ID or date is invalid?

The actor may record an error row with relevant input details and continue where possible. Other valid player IDs may still be processed.

#### How many records can one run save?

The default limit is 100 successful records, and the maximum is 1,000. The number of records returned also depends on the selected mode and available data.

#### Can I schedule recurring exports?

Yes. Use Apify scheduling to refresh daily schedules, team information, rosters, or player records.

#### Which export formats are supported?

The collected dataset can be exported as JSON, CSV, or Excel.

### Trademark Notice

MLB and related names, logos, and trademarks belong to their respective owners. Their use in this documentation is solely to identify the source of the data and does not imply affiliation, sponsorship, endorsement, or partnership.

### Disclaimer

This actor is an independent tool and is not affiliated with, endorsed by, sponsored by, or otherwise officially associated with MLB or its owners. Users are responsible for complying with applicable source terms, copyright restrictions, attribution requirements, and other relevant laws when using or redistributing collected information.

### Is Web Scraping Legal?

Collecting information that is already public is generally legal. Scraping is not the same thing as hacking, and there is no single law that bans it. The limits are the usual ones: do not break into accounts, do not take private or confidential data, and be careful with personal data and copyrighted works. A site's terms can also restrict how you access it. Facts such as a public name, price, or rating are not the same thing as republishing someone's article or photo.

This actor collects information from public pages. It does not log in and it does not bypass access controls.

For a longer explanation, see Apify's article [Is web scraping legal?](https://blog.apify.com/is-web-scraping-legal/).

# Actor input Schema

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

What to collect: schedule for one date, team for a club profile, roster for the active roster, or player for people by id. The value teams is accepted as team.

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

Schedule date in YYYY-MM-DD. Used only when mode is schedule. Verified example: 2026-09-15.

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

MLB team id for team and roster modes. 108 is the Los Angeles Angels.

## `personIds` (type: `array`):

Player ids, one per line, used when mode is player. 660271 is Shohei Ohtani.

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

Maximum successful rows to save this run. Values are clamped between 1 and 1000.

## `timeoutSecs` (type: `integer`):

Stop the run after this many seconds and keep rows already saved.

## `requestTimeoutSecs` (type: `integer`):

How long to wait for each stats API response before retrying.

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

Optional proxy for requests. Leave Apify Proxy off unless the stats host blocks your IP.

## Actor input object example

```json
{
  "mode": "schedule",
  "date": "2026-09-15",
  "teamId": 108,
  "personIds": [
    "660271",
    "624428"
  ],
  "maxItems": 100,
  "timeoutSecs": 300,
  "requestTimeoutSecs": 30,
  "proxyConfiguration": {
    "useApifyProxy": false
  }
}
```

# Actor output Schema

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

Default dataset with one row per team, game, roster spot, player, or error.

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

Dataset items in the overview table view.

# 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": "2026-09-15",
    "teamId": 108,
    "personIds": [
        "660271"
    ],
    "maxItems": 100,
    "timeoutSecs": 300,
    "requestTimeoutSecs": 30,
    "proxyConfiguration": {
        "useApifyProxy": false
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("real-estate-api/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": "2026-09-15",
    "teamId": 108,
    "personIds": ["660271"],
    "maxItems": 100,
    "timeoutSecs": 300,
    "requestTimeoutSecs": 30,
    "proxyConfiguration": { "useApifyProxy": False },
}

# Run the Actor and wait for it to finish
run = client.actor("real-estate-api/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": "2026-09-15",
  "teamId": 108,
  "personIds": [
    "660271"
  ],
  "maxItems": 100,
  "timeoutSecs": 300,
  "requestTimeoutSecs": 30,
  "proxyConfiguration": {
    "useApifyProxy": false
  }
}' |
apify call real-estate-api/mlb-stats-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,real-estate-api/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/cwxOFL6oy1vbyCW9V/builds/T9avhfQTgtJcEP9Fg/openapi.json
