# Trenitalia Train Ticket and Connection Scraper (`muhammadafzal/trenitalia-train-ticket-connection-scraper`) Actor

Scrape Trenitalia train connections, departure and arrival times, duration, train numbers, current starting prices, service classes, fare offers, availability, and direct or connecting itineraries.

- **URL**: https://apify.com/muhammadafzal/trenitalia-train-ticket-connection-scraper.md
- **Developed by:** [Muhammad Afzal](https://apify.com/muhammadafzal) (community)
- **Categories:** Travel, Automation, Other
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $3.00 / 1,000 train connections

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#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

## Trenitalia Train Ticket and Connection Scraper

Search Trenitalia routes and export one structured dataset record per train connection. Results include departure and arrival times, duration, direct/connecting status, train categories and numbers, current starting prices, service classes, fare names, fare conditions, and reported seat availability.

This Actor is read-only. It does not log in, reserve seats, modify carts, book journeys, buy tickets, or process payments.

### What you can collect

- Trenitalia connection IDs and sale status
- departure and arrival station names and timestamps
- total duration, change count, and direct-train flag
- starting ticket price and currency
- every train leg, category, acronym, and train number
- optional fare offers by service class, including price, refund/change flags, sale status, and reported availability
- outbound and optional return searches

### Input

Provide `from` and `to`. Add `departureDate` for a specific day; when omitted, the Actor searches tomorrow so saved Tasks remain runnable. Times are interpreted in Italy's `Europe/Rome` time zone.

```json
{
  "from": "Roma Termini",
  "to": "Firenze S. M. Novella",
  "departureDate": "2026-09-10",
  "departureTime": "08:00",
  "adults": 1,
  "children": 0,
  "trainType": "all",
  "directOnly": false,
  "sortBy": "DEPARTURE_DATE",
  "includeOffers": true,
  "maxResults": 20,
  "maxPages": 5
}
```

Add `returnDate` and optionally `returnTime` to run a second, reverse-direction connection search in the same run. For return searches, `maxResults` is split between outbound and return records. Supported train filters are `all`, `frecce`, `intercity`, and `regional`. Supported sorting values are `DEPARTURE_DATE`, `ARRIVAL_DATE`, and `FASTEST`.

### Output example

```json
{
  "connectionId": "x73eaa9a6-d8cc-4d27-be44-ccf01111f78b",
  "searchDirection": "outbound",
  "origin": "Roma Termini",
  "destination": "Firenze S. M. Novella",
  "departureTime": "2026-09-10T08:05:00.000+02:00",
  "arrivalTime": "2026-09-10T09:46:00.000+02:00",
  "duration": "1h 41min",
  "durationMinutes": 101,
  "changes": 0,
  "direct": true,
  "status": "SALEABLE",
  "price": 55,
  "currency": "EUR",
  "priceIndicative": false,
  "trains": [{
    "origin": "Roma Termini",
    "destination": "Firenze S. M. Novella",
    "departureTime": "2026-09-10T08:05:00.000+02:00",
    "arrivalTime": "2026-09-10T09:46:00.000+02:00",
    "trainCategory": "Frecciarossa",
    "trainAcronym": "FR",
    "trainNumber": "9516"
  }],
  "fareOffers": [{
    "service": "STANDARD",
    "offer": "BASE",
    "price": 55,
    "currency": "EUR",
    "availableSeats": 151,
    "status": "SALEABLE",
    "refundable": true,
    "changeable": true
  }]
}
```

The `OUTPUT` key-value-store record reports `DATA`, `EMPTY`, `PARTIAL`, `BLOCKED`, `REJECTED`, or `FAILED`, along with source-page counts, record/event-charge parity, resolved stations, and warnings.

### Pricing

The Actor uses pay per event:

- **Actor start:** $0.005 per run
- **Train connection:** $0.003 per dataset record

A 20-result run costs up to $0.065 in Actor event charges. Apify dataset/storage operations may appear separately under your platform plan. The Actor saves each result before charging and stops when the run's maximum event charge is reached.

### Accuracy and limitations

- Prices and availability are live search snapshots and can change before checkout.
- `price` is the starting price Trenitalia reports for the complete connection and selected passenger counts.
- Station queries resolve through Trenitalia autocomplete. Use the full station name when several stations have similar names.
- Connections depend on the timetable sales horizon and service availability for the chosen date.
- The source is Trenitalia's public journey-search flow. Endpoint changes, maintenance, rate limits, or access challenges can temporarily block a run; the Actor reports those conditions instead of fabricating records.
- Use the data in accordance with Trenitalia's applicable terms, robots/access rules, and local law. Trenitalia is a trademark of its owner; this independent Actor is not affiliated with or endorsed by Trenitalia.

### API use

Run the Actor through Apify API, schedules, integrations, or MCP and read the default dataset. `maxResults` is the hard output bound; `maxPages` is a second safety bound for source requests.

# Actor input Schema

## `from` (type: `string`):

Trenitalia departure station name, such as Roma Termini, Milano Centrale, or Firenze S. M. Novella.

## `to` (type: `string`):

Trenitalia arrival station name.

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

Travel date in YYYY-MM-DD format, interpreted in Europe/Rome. Leave empty to search tomorrow, which keeps saved Tasks evergreen.

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

Earliest departure time in 24-hour HH:MM format, Italy local time.

## `returnDate` (type: `string`):

Add a return journey using YYYY-MM-DD. Leave empty for one way.

## `returnTime` (type: `string`):

Earliest return time in 24-hour HH:MM format. Used only with returnDate.

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

Number of adult passengers used for ticket-price and availability searches.

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

Number of child passengers used for ticket-price and availability searches.

## `trainType` (type: `string`):

Search all main connections or restrict results to a Trenitalia service family.

## `directOnly` (type: `boolean`):

Return connections with no train changes when available.

## `sortBy` (type: `string`):

Order connections by departure, arrival, or journey duration.

## `includeOffers` (type: `boolean`):

Include available service classes and fare conditions, prices, and seat availability reported by Trenitalia.

## `maxResults` (type: `integer`):

Maximum dataset records. Each delivered connection is one billable result event.

## `maxPages` (type: `integer`):

Safety bound for pagination. Trenitalia typically returns up to 10 connections per page.

## Actor input object example

```json
{
  "from": "Roma Termini",
  "to": "Firenze S. M. Novella",
  "departureTime": "08:00",
  "adults": 1,
  "children": 0,
  "trainType": "all",
  "directOnly": false,
  "sortBy": "DEPARTURE_DATE",
  "includeOffers": true,
  "maxResults": 20,
  "maxPages": 5
}
```

# Actor output Schema

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

No description

## `summary` (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 = {
    "from": "Roma Termini",
    "to": "Firenze S. M. Novella"
};

// Run the Actor and wait for it to finish
const run = await client.actor("muhammadafzal/trenitalia-train-ticket-connection-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 = {
    "from": "Roma Termini",
    "to": "Firenze S. M. Novella",
}

# Run the Actor and wait for it to finish
run = client.actor("muhammadafzal/trenitalia-train-ticket-connection-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 '{
  "from": "Roma Termini",
  "to": "Firenze S. M. Novella"
}' |
apify call muhammadafzal/trenitalia-train-ticket-connection-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,muhammadafzal/trenitalia-train-ticket-connection-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/RSDdO2N0QBnOZSGEu/builds/GcZ67fDf4eexAc2lN/openapi.json
