# Trenitalia Timetable Scraper - Solutions, Fares & Status (`rl1987/trenitalia-timetable-scraper`) Actor

Collect Trenitalia journey solutions and fares with seats left, live train status with stops, station boards and station ids as flat JSON. Four modes, six dataset views, scrapedAt and provenance on every row; no login or API key.

- **URL**: https://apify.com/rl1987/trenitalia-timetable-scraper.md
- **Developed by:** [R.L.](https://apify.com/rl1987) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.69 / 1,000 journey rows

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

## Trenitalia Timetables Scraper - Solutions, Fares, Train Status, Station Boards

This Actor collects Trenitalia journey options, fares and seats left, live train running status, stop sequences, station departure and arrival boards, and station ids as flat JSON rows. One `mode` input selects the slice: `search`, `trainStatus`, `stationBoard` or `stations`. All four write to one dataset with six views and a `recordType` on every row: `solution`, `fare`, `trainStatus`, `stop`, `board` or `station`. In the recorded Milano Centrale to Roma Termini search for 2026-11-21, the fixture produced 5 solution rows and 7 fare rows; train 9611 produced 1 status row and 6 stop rows; the Milano Centrale boards held 34 departures and 47 arrivals. Rows come from Trenitalia's own Android BFF at `https://app.lefrecce.it/Channels.Mobile.BFF/api/`, recorded live on 2026-11-19, not from a rendered page. No Trenitalia account, login or API key is used. The Actor is read-only: it calls no cart, reservation or ticket purchase endpoint. Full field-by-field schemas: https://keyspace.dev/data-dictionaries/trenitalia/index.html

### What can I collect from Trenitalia?

Four modes cover the data the anonymous timetable surface exposes. Each view returns only the columns its row kind fills.

| `mode` | Input used | Dataset view / `recordType` | Main columns | Charge event |
| --- | --- | --- | --- | --- |
| `search` (default) | `origin`, `destination`, `departureDate` | `solutions` / `solution`, `fares` / `fare` | `solutionId`, `searchId`, `origin`, `destination`, `departureTime`, `arrivalTime`, `duration`, `numberOfChanges`, `trainSummary`, `legCount`, `fareCount`; `serviceName`, `fareName`, `availableSeats`, `canRefund`, `canChange`, `canModify` | `solution-row`, `fare-row` |
| `trainStatus` | `trainNumbers` | `trainStatuses` / `trainStatus`, `stops` / `stop` | `rideKey`, `departureDate`, `delay`, `runningStatus`, `lastTakeoverLocation`, `stopCount`, `reachedStops`; `sequence`, `location`, `platform`, `scheduledDeparture`, `actualDeparture`, `actualArrival` | `train-status-row`, `stop-row` |
| `stationBoard` | `boardStation`, `boardDirection` | `boards` / `board` | `direction`, `boardStation`, `boardStationId`, `time`, `origin`, `destination`, `delay`, `scheduledPlatform`, `actualPlatform` | `board-row` |
| `stations` | `stationQuery` | `stations` / `station` | `stationId`, `name`, `isCityAggregate`, `bus`, `bdo`, `query` | `station-row` |

Every row also carries `scrapedAt`, the UTC delivery time stamped by the ledger, and `provenance`, the Actor build and row kind, for example `local@local solution`. A column another mode does not fill is absent from the row rather than null. Each of the six row kinds has its own billable event, named in the table.

### What does one row contain?

The six views have 21, 19, 15, 15, 15 and 7 fields respectively. The counts below come from mapping the recorded BFF responses, not from a synthetic stub.

- **`solution` (21 columns).** One journey option. All 5 recorded rows filled all 21 view columns: route, ISO departure and arrival with the API's `+01:00` offset, `duration` as the API formats it (`3h 10min`), `numberOfChanges` as Italian text (`Diretto`, `1 Cambio`, `2 Cambi`), `status` (`SALEABLE`), `trainCategory` (`Frecciarossa`), `trainNumber`, `trainAcronym`, `trainSummary`, `legCount`, `fareCount`, `priceIsIndicative` and the upstream seat-map and grid flags. `searchId` groups the solutions of one query.
- **`fare` (19 columns).** One selected offer on a journey, emitted only when `includeFares` is on. The recorded search produced 7 fare rows, all 7 with `serviceName`, `fareName`, `availableSeats` and the refund and change flags filled. `serviceId` 30005 is Standard on Frecciarossa, 170 is 2ª Classe Easy on Intercity and 286 is 2ª Classe Prenotazione. Fare families in that sample were `BASE` and `ORDINARIA`; the `ORDINARIA` rows had `canRefund`, `canChange` and `canModify` all false. All 7 rows had `offerStatus` `NOT_SALEABLE` and `selectable` false while their solution was `SALEABLE`, so read both fields before treating a row as purchasable. A fare row repeats the journey's `price` and `currency` because the upstream offer details carry none of their own.
- **`trainStatus` (15 columns).** One dated run. The train 9611 response gave `rideKey` `09611A`, `departureDate` `19/11/2026`, origin Torino Porta Nuova, destination Napoli Centrale, `delay` `+4 MIN`, `runningStatus` `BEHIND_SCHEDULE`, `lastTakeoverLocation` Napoli Centrale, `lastTakeoverTime` `19/11/2026 - 12:37`, `stopCount` 6 and `reachedStops` 6.
- **`stop` (15 columns).** One stop in that run, with `sequence` 1 to 6, string `locationId` (`830001700` at Milano Centrale), `platform`, `trainOrientation` (`Executive in testa`), `stopStatus` and `reached`. Five stops had `STATION_EXCEEDED` and the last had `IN_STATION`. At Milano Centrale the scheduled departure was 08:00 and the actual departure 08:02. The terminus at Napoli Centrale has no departure times, only arrival times.
- **`board` (15 columns).** One train on a station board. The Milano Centrale recordings held 34 departures and 47 arrivals. `delay` is the API's string (`Partito +2 MIN`, `Non partito`, `Arrivato +43 MIN`); `scheduledPlatform` and `actualPlatform` are separate so a platform change is visible. `actualPlatform` was null on 24 of the 34 departure rows and 38 of the 47 arrival rows. On arrivals, `origin` is the train's true starting station, not a neighbour of the board station.
- **`station` (7 columns).** One name match. The query `Milano` returned 30 rows: `830001650` "Milano ( Tutte Le Stazioni )" first with `isCityAggregate` true, then `830001700` Milano Centrale and `830001645` Milano Porta Garibaldi. 27 of the 30 rows had `bdo` true and all 30 had `bus` false. `Roma Termini` resolved to numeric id `830008409`.

Time and date strings keep the source format. Solutions use ISO values such as `2026-11-21T08:00:00.000+01:00`; a status endpoint returns `19/11/2026` while a trainKey carries `2026-11-19T06:50:00`. In the 47-row arrivals board, 43 rows used the trainKey's date-only `2026-11-19T00:00:00` fallback and 4 carried the board's own full timestamp. `time` is always the time shown on the board, such as 19:35.

### Which journeys and stations did the recorded runs cover?

The recorded Milano Centrale to Roma Termini search was run from 08:00 for travel on 2026-11-21. It returned five journeys with these lead trains:

| Departure | Train(s) | `numberOfChanges` | `duration` | `legCount` | Fare rows |
| --- | --- | --- | --- | --- | --- |
| 08:00 | FR 9611 Frecciarossa | Diretto | 3h 10min | 1 | 1 |
| 08:05 | IC 657 Intercity, RV 4133 Regionale Veloce via Pisa Centrale | 1 Cambio | 9h 43min | 2 | 2 |
| 08:10 | FR 9519 Frecciarossa | Diretto | 3h 39min | 1 | 1 |
| 08:16 | BU BUS L609A | 2 Cambi | 14h 19min | 3 | 2 |
| 08:30 | FR 9613 Frecciarossa | Diretto | 3h 11min | 1 | 1 |

Train 9611's status run covered six stops from Torino Porta Nuova to Napoli Centrale: Torino Porta Nuova, Torino Porta Susa, Milano Centrale, Bologna Centrale, Roma Termini and Napoli Centrale. The Milano Centrale departures board included FR 9663 to Napoli Centrale at 19:35 on platform 17, RE 25532 to Chiasso at 19:43 and ICN 35051 to Lecce at 19:45. Its arrivals board included FR 8824 from Lecce at 19:10 with `Arrivato +43 MIN`. Station ids used by these requests include `830001700` for Milano Centrale, `830008409` for Roma Termini and `830005043` for Bologna Centrale.

### How does a search cover a whole day?

`maxSolutions` sets the day total, from 1 to 100, with a default of 5. Trenitalia serves only a forward window of about 10 journeys from `departureTime`, and caps a single call at 20, so the Actor walks successive windows from just past the last journey seen. It stops after collecting `maxSolutions`, when the day's schedule ends, at 40 windows, or when the delivery ledger stops. `departureTime` is a time of day in 24-hour HH:MM form, default `08:00`.

`service` filters by `all`, `frecce`, `intercity` or `regional`; `order` has four values, sent to the API as departure, arrival, fastest and fare-based ordering. `adults` runs from 1 to 9 and `children` from 0 to 9; these change the quoted price context, not which journeys are listed. `includeFares` is on by default and adds one `fare` row for each selected offer: a 5-journey search with 2 offers each gives 5 solution rows and 10 fare rows. Turn it off for timetable-only runs.

### How are live status, boards and limits handled?

`trainStatus` accepts up to 25 numbers in `trainNumbers`; duplicates are dropped before requests, and each number gets its own lookup because all those POSTs share one URL. A number can resolve to more than one dated run. Each run yields one `trainStatus` row and one `stop` row per stop, and the full trainKey is forwarded because sending only the `rideKey` returns empty stops. `rideKey` plus `departureDate` identifies a run.

`stationBoard` resolves `boardStation` against Trenitalia's station list, then reads either `departures` or `arrivals`. A board lists through-services: an arrival row's `origin` and `destination` describe the train's own endpoints, while `boardStation` names the station queried. `stations` does a substring match on `stationQuery` and returns city aggregates alongside physical stations; it finds exact names for the other modes.

`maxItems` defaults to 0, meaning no limit. It stops after that many rows have been delivered, counted by the ledger after de-duplication and across all row kinds of the run. A run also stops when it reaches the maximum total charge set on the run itself, and says so in its status message. `maxConcurrency` defaults to 5, `maxRequestsPerCrawl` to 0 (unlimited), `maxRequestRetries` to 5 and `maxSessionRotations` to 10; blocked status codes get a fresh session, proxy and device identity under the last of these budgets.

### What happens when input, requests or rows fail?

Everything that can be checked is checked before the first network call. A missing `origin`, identical origin and destination, an impossible date such as 2026-02-30, a time such as 25:00, `maxSolutions` above 100, an unknown mode or more than 25 train numbers all end with a "Nothing to scrape" status message and no rows. An unresolved station name stops a search or board rather than guessing an id; `stations` returns no rows for a name that matches nothing; a train number with no run and an empty status payload deliver nothing.

The BFF answers HTTP 200 even for some refusals, so the Actor reads `responseInfo.status` from the body. `UNAUTHORIZED` and `CLIENT_NOT_SUPPORTED` are fatal; challenge pages and 401, 403 or 429 responses go through the retry and rotation path. Before a row is written or billed, the ledger removes duplicates (`solutionId` for solutions, `solutionId` plus `offerId` plus `serviceId` for fares, `rideKey` plus `departureDate` for runs), drops rows that resolve no entity and validates the row against the shipped dataset schema. Rows cut by `maxItems` or the run charge cap are not delivered. The input accepts an Apify Proxy or custom proxies; the recorded responses were fetched from a datacenter IP on 2026-11-19.

### What do people ask before running this?

**Do I need a Trenitalia account or API key?**\
No. The Actor calls the public mobile BFF anonymously with a generated Android device id.

**Can it book a ticket, hold a seat or read my orders?**\
No. It is read-only, and full seat maps need a logged-in cart, which is out of scope. Seats left per class are in `availableSeats` on fare rows.

**How do I get a whole day of departures instead of the next hour?**\
Set `maxSolutions` up to 100. The Actor walks successive time windows from `departureTime` until it has that many journeys or the day ends.

**Why did one train number return two status rows?**\
The number resolved to more than one dated run. Use `rideKey` and `departureDate` to tell them apart.

**What if a station name does not match?**\
A search or board run stops without delivering a row, rather than searching a guessed station id. Use `stations` with part of the name to find the spelling it needs.

**How do I bound the size of a run?**\
Use `maxItems` for delivered rows and `maxSolutions` for journeys within a search. The run's own maximum charge is a second stop condition.

**Can I schedule it?**\
Yes. It is an Apify Actor, so it can be started from the Console, the Apify API or a schedule with the same input fields.

**Where are the full schemas and charge rates?**\
The 21 input fields, all six dataset views and the six row-level charge events are documented at https://keyspace.dev/data-dictionaries/trenitalia/index.html. Current rates are on this Actor's Pricing tab.

### Where are the full input and output schemas?

The input reference covers 21 fields (`mode`, the four search fields, passenger counts, service and sort, `maxSolutions`, `includeFares`, `trainNumbers`, the two board fields, `stationQuery`, `maxItems` and the five advanced fields). The six dataset views hold 92 field definitions in total, and the output maps each view to its own dataset URL. All of them are documented here: https://keyspace.dev/data-dictionaries/trenitalia/index.html

# Actor input Schema

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

Which of the four modes to run. Search resolves two station names and returns the journeys between them with fares and seats left; Train status follows a train number's current run and stops; Station board reads a station's departures or arrivals board; Stations returns station ids for a name.

## `origin` (type: `string`):

Departure station NAME, e.g. 'Milano Centrale'. Resolved against Trenitalia's own station list; an exact name wins, otherwise the first non-city match. A name that matches nothing stops the run instead of guessing a station id.

## `destination` (type: `string`):

Arrival station NAME, e.g. 'Roma Termini'. Must differ from the origin.

## `departureDate` (type: `string`):

Date of travel (YYYY-MM-DD). Timetables are published months ahead, but a date far in the past returns nothing.

## `departureTime` (type: `string`):

Earliest departure time to search from, 24-hour HH:MM (default 08:00). This is a time of day, not a date, so it is typed rather than picked.

## `adults` (type: `integer`):

Number of adult passengers. Sent as the API's `adults`; it does not change which journeys are listed, only the price context the upstream quotes.

## `children` (type: `integer`):

Number of child passengers (0-9). Sent as the API's `children`.

## `service` (type: `string`):

Filter the journeys by service family: all, Frecce (high speed), Intercity or Regional. Maps to the API's `criteria.selectedTypeTrips`.

## `order` (type: `string`):

How the API sorts the journeys: by departure, by arrival, fastest or cheapest. Maps to `criteria.order`.

## `maxSolutions` (type: `integer`):

How many journey options to collect for the day, 1-100. The API serves only a forward window of ~10 journeys from departureTime, so the Actor walks successive time windows (each ≤20, the upstream per-request cap) until it has this many or the day ends. One row per journey, plus one per fare when includeFares is on.

## `includeFares` (type: `boolean`):

Fetch the fare rows too (travel class, fare family, refund/change flags, seats left). ON BY DEFAULT AND BILLED SEPARATELY: every fare is its own charged row, so a 5-journey search with 2 fares each bills 5 solution rows plus 10 fare rows. Turn it off when you only need the timetable.

## `trainNumbers` (type: `array`):

One or more train numbers to follow, e.g. 9611. Each number resolves to its current run(s) and each run produces one trainStatus row plus one stop row per stop. Up to 25 numbers per run.

## `boardStation` (type: `string`):

Station NAME whose board to read, e.g. 'Milano Centrale'. Resolved against Trenitalia's station list; a name that matches nothing queues no board.

## `boardDirection` (type: `string`):

Departures or arrivals for that station. On an arrivals board the row's `origin` is where the train came from and `destination` is the board station.

## `stationQuery` (type: `string`):

Text to match against Trenitalia's station list, e.g. 'Milano' or 'Termini'. The match is a substring filter, so a name that does not exist returns no rows rather than a page of near misses. Use this mode to find the exact name another mode needs.

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

Stop after this many rows have been DELIVERED (0 = no limit). Counted by the billing ledger after de-duplication and across ALL row kinds of the run, so it is a limit on what you receive and pay for, not on what the target returned.

## `maxConcurrency` (type: `integer`):

Max number of requests processed in parallel.

## `maxRequestsPerCrawl` (type: `integer`):

Safety cap on total requests. 0 = unlimited.

## `maxRequestRetries` (type: `integer`):

Retries per request before it's marked failed. Does NOT bound retries caused by a blocked/rate-limited status code (401/403/429 by default) - see maxSessionRotations for that.

## `maxSessionRotations` (type: `integer`):

Retries for a blocked/rate-limited status code (401/403/429 by default - see src/errors.py), each with a fresh session/proxy and a fresh CustomerDeviceId. Separate budget from maxRequestRetries.

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

Apify Proxy or your own proxies. The target answered from a datacenter IP when measured on 2026-11-19, so residential is not required; switch it on if a run starts seeing 403s.

## Actor input object example

```json
{
  "mode": "search",
  "departureTime": "08:00",
  "adults": 1,
  "children": 0,
  "service": "all",
  "order": "departure",
  "maxSolutions": 5,
  "includeFares": true,
  "boardDirection": "departures",
  "maxItems": 0,
  "maxConcurrency": 5,
  "maxRequestsPerCrawl": 0,
  "maxRequestRetries": 5,
  "maxSessionRotations": 10,
  "proxyConfiguration": {
    "useApifyProxy": true
  }
}
```

# Actor output Schema

## `solutions` (type: `string`):

No description

## `fares` (type: `string`):

No description

## `trainStatuses` (type: `string`):

No description

## `stops` (type: `string`):

No description

## `boards` (type: `string`):

No description

## `stations` (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 = {};

// Run the Actor and wait for it to finish
const run = await client.actor("rl1987/trenitalia-timetable-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 = {}

# Run the Actor and wait for it to finish
run = client.actor("rl1987/trenitalia-timetable-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 '{}' |
apify call rl1987/trenitalia-timetable-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,rl1987/trenitalia-timetable-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/J4lw0F79zTubsgrW2/builds/IHv7IvfOTbU2Xq6pd/openapi.json
