# Baseball Reference Stats Scraper (`muhammadafzal/baseball-reference-stats-scraper`) Actor

Extract authorized Baseball Reference player batting, pitching, fielding, WAR, team, season, and career-total statistics for sports research and analytics.

- **URL**: https://apify.com/muhammadafzal/baseball-reference-stats-scraper.md
- **Developed by:** [Muhammad Afzal](https://apify.com/muhammadafzal) (community)
- **Categories:** Automation
- **Stats:** 2 total users, 1 monthly users, 57.1% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $16.00 / 1,000 player profile 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/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

## Baseball Reference Stats Scraper

> **Free-plan limit:** Apify free-plan runs can return at most **5 dataset records per run** from this Actor, even if you request more.

Extract authorized Baseball Reference player batting, pitching, and fielding statistics into analysis-ready JSON, CSV, Excel, or API records. Each dataset item represents one player-season table row and includes both normalized headline fields and every source `data-stat` value.

> Authorization required: Sports Reference states that tools based on scraped site data require permission. Use this Actor only under your written permission or data license and follow the request limits attached to that authorization.

### What it extracts

| Field group | Examples |
|---|---|
| Player | `playerId`, `playerName`, `position`, `bats`, `throws` |
| Row identity | `statType`, `tableId`, `rowType`, `season`, `team`, `league`, `age` |
| Batting | `games`, `plateAppearances`, `atBats`, `hits`, `homeRuns`, `runsBattedIn`, `stolenBases`, `battingAverage`, `onBasePercentage`, `sluggingPercentage`, `onBasePlusSlugging`, `war` |
| Pitching | `wins`, `losses`, `earnedRunAverage`, `inningsPitched`, `strikeouts`, `war` |
| Complete row | `stats`, keyed by Baseball Reference's stable `data-stat` attributes |
| Provenance | `sourceUrl`, `scrapedAt` |

Use it for authorized sports research, historical player analysis, fantasy-baseball pipelines, and spreadsheet exports. It accepts public Baseball Reference player pages only. It does not scrape Stathead, search results, team pages, league registers, game logs, splits, projections, or authenticated content.

The Actor uses the owner's DataImpulse proxy through the `DATAIMPULSE_PROXY_URL` secret. No proxy setting is required in run input.

### Input

| Input | Purpose | Default |
|---|---|---|
| `playerIds` | Baseball Reference IDs such as `troutmi01` | `['troutmi01']` |
| `startUrls` | Full `https://www.baseball-reference.com/players/...` URLs | none |
| `statTypes` | `batting`, `pitching`, and/or `fielding` | all three |
| `seasons` | Optional four-digit season allowlist | every season |
| `includeCareerTotals` | Include aggregate rows such as `14 Yrs` | `false` |
| `maxPlayers` | Unique player-page cap | `5` |
| `maxRows` | Dataset-row cap | `500` |

Example:

```json
{
  "playerIds": ["troutmi01", "ohtansh01"],
  "statTypes": ["batting", "pitching"],
  "seasons": [2023, 2024],
  "includeCareerTotals": false,
  "maxPlayers": 2,
  "maxRows": 100
}
```

API call:

```bash
curl -X POST "https://api.apify.com/v2/acts/muhammadafzal~baseball-reference-stats-scraper/runs?token=YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"playerIds":["troutmi01"],"statTypes":["batting"],"maxPlayers":1}'
```

### Output

```json
{
  "playerId": "troutmi01",
  "playerName": "Mike Trout",
  "statType": "batting",
  "tableId": "players_standard_batting",
  "rowType": "season",
  "season": 2024,
  "age": 32,
  "team": "LAA",
  "league": "AL",
  "games": 29,
  "plateAppearances": 126,
  "atBats": 109,
  "hits": 24,
  "homeRuns": 10,
  "runsBattedIn": 14,
  "stolenBases": 6,
  "battingAverage": 0.22,
  "onBasePercentage": 0.325,
  "sluggingPercentage": 0.541,
  "onBasePlusSlugging": 0.866,
  "war": 0.9,
  "stats": {
    "year_ID": 2024,
    "team_name_abbr": "LAA",
    "HR": 10,
    "batting_avg": 0.22
  },
  "sourceUrl": "https://www.baseball-reference.com/players/t/troutmi01.shtml",
  "scrapedAt": "2026-08-29T12:00:00.000Z"
}
```

The `OUTPUT` key-value-store record distinguishes `SUCCEEDED`, `SUCCEEDED_WITH_WARNINGS`, `EMPTY`, `BLOCKED`, `INVALID_INPUT`, and `FAILED`. Diagnostics never appear as fake player rows.

### Pricing

This Actor uses **pay-per-event** pricing. These are the current Apify Store event prices:

| Event | Price (USD) | When it is charged |
|---|---:|---|
| `player-scraped` | FREE: $0.02; BRONZE: $0.02; SILVER: $0.02; GOLD: $0.016; PLATINUM: $0.016; DIAMOND: $0.016 | Player profile scraped — One player page successfully parsed and delivered as season-stat rows. |
| `apify-actor-start` | $0.005 | Actor Start — Charged when the Actor starts running. Number of events charged depends on Actor memory (one event per GB, minimum one event). — Charged once per run. |

Apify platform usage for this Actor run is included alongside the event prices above; no separate per-run platform-usage fee is passed to users.

This covers Apify platform usage for this Actor run. Other Apify products or usage outside this Actor run may still follow your account plan.

### Reliability and limits

The scraper uses one consistent browser session, no more than eight page requests per minute, bounded retries, canonical URL deduplication, and a US residential proxy by default. Plain HTTP currently receives a managed access challenge. If a permitted browser session is still challenged, the Actor reports `BLOCKED`, returns zero fabricated rows, and applies no player-result charge. It does not solve CAPTCHAs or bypass authenticated access controls.

Tables legitimately absent from a player page are warnings, not fabricated empty records. Use `statTypes` to request only tables relevant to the player. `maxRows` can stop a run after a partial but valid dataset.

### Legal and compliance

You are responsible for ensuring that your Sports Reference permission or license covers automated collection, storage, and downstream use. Do not use the output to violate privacy, intellectual-property, database, contract, or applicable sports-betting laws. The Actor is not affiliated with Sports Reference LLC or Major League Baseball and does not include third-party branding.

For support, include the Apify run ID, selected player IDs, expected table, and redacted `OUTPUT` record. Never post authentication tokens or proxy URLs.

### Use cases

- Schedule repeatable collection and export results to downstream workflows.
- Run a one-off research job and export the structured result as JSON, CSV, Excel, XML, or RSS from Apify.
- Schedule the same input to monitor changes over time and send completed datasets to a webhook or integration.
- Feed schema-shaped records into a database, spreadsheet, BI tool, or AI workflow with the source URL retained for verification.

# Actor input Schema

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

Use this when you know Baseball Reference IDs, such as troutmi01. Accepts 1–25 IDs; this is not an MLBAM ID list.

## `startUrls` (type: `array`):

Use this for full public player URLs in the form https://www.baseball-reference.com/players/t/troutmi01.shtml. Team, league, search, and Stathead URLs are not supported.

## `statTypes` (type: `array`):

Use this to select standard player tables. Defaults to batting, pitching, and fielding; unavailable tables are reported as warnings.

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

Use this to keep specific four-digit seasons, for example 2024. Leave empty for every season; totals are controlled separately.

## `includeCareerTotals` (type: `boolean`):

Use this to include non-season total rows such as Career or 15 Yrs. Defaults to false so the dataset contains season rows only.

## `maxPlayers` (type: `integer`):

Use this to cap processed unique player pages after deduplication. Defaults to 5; allowed range is 1–25.

## `maxRows` (type: `integer`):

Use this as a hard dataset-row cap across all players. Defaults to 500; allowed range is 1–5,000.

## Actor input object example

```json
{
  "playerIds": [
    "troutmi01"
  ],
  "statTypes": [
    "batting",
    "pitching",
    "fielding"
  ],
  "seasons": [],
  "includeCareerTotals": false,
  "maxPlayers": 5,
  "maxRows": 500
}
```

# Actor output Schema

## `results` (type: `string`):

Schema-validated rows in the default dataset.

## `output` (type: `string`):

Outcome, counts, billing, warnings, and blocked URLs.

# 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 = {
    "playerIds": [
        "troutmi01"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("muhammadafzal/baseball-reference-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 = { "playerIds": ["troutmi01"] }

# Run the Actor and wait for it to finish
run = client.actor("muhammadafzal/baseball-reference-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 '{
  "playerIds": [
    "troutmi01"
  ]
}' |
apify call muhammadafzal/baseball-reference-stats-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,muhammadafzal/baseball-reference-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/sHL863j5CkU2Dk0i9/builds/7ZxIIvqHJYobMQSzI/openapi.json
