# Trainline Scraper (`crawlerbros/trainline-scraper`) Actor

Scrape Trainline - the UK & Europe rail/bus metasearch. Journey search (origin → destination → date/time) with departure/arrival times, duration, changes, operator and fares; station autocomplete lookup; and popular routes with 'from' prices.

- **URL**: https://apify.com/crawlerbros/trainline-scraper.md
- **Developed by:** [Crawler Bros](https://apify.com/crawlerbros) (community)
- **Categories:** Travel, Automation, E-commerce
- **Stats:** 1 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $3.00 / 1,000 results

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.
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?

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

## Trainline Scraper

Scrape **Trainline** — Europe's leading rail & bus ticket metasearch (UK, France, Germany, Italy, Spain and 40+ countries). Search train journeys between stations or cities, look up stations with codes and coordinates, and pull Trainline's own popular routes with "from" prices. Browser-based (Playwright) for the journey search flow, with public JSON endpoints for station lookup and popular routes. No login, no cookies required.

### What this actor does

- **Three modes:** `search` (journeys), `stationLookup` (station autocomplete), `popularRoutes` (curated route list)
- **Journey search:** origin → destination → date → time, with departure/arrival times, duration, changes, operator, price and currency
- **Reliable fallback:** when the live fare engine blocks automated access, the actor automatically emits the server-rendered route summary (first/last train, average & fastest journey time, frequency, distance, price-from, operators) instead of failing
- **Station autocomplete:** names, station IDs, coordinates, countries, timezones and available connections
- **Filters:** depart-after / arrive-by times, ticket type (Standard / First / Season), max price
- **Locales & currencies:** 18 site locales and 24 ISO 4217 currencies
- **Empty fields are omitted**

### Data Source

Trainline (www.thetrainline.com). Station lookup and popular routes come from Trainline's public JSON endpoints. Journey search runs the browser-based results flow.

### Limitations

- Trainline's live fare engine (`/api/journey-search/`) is protected by DataDome bot detection. From some datacenter IPs it returns a CAPTCHA challenge and no journeys. When this happens, `search` mode **automatically falls back** to the server-rendered route-summary page, which is reliably accessible and still yields real data (first/last train, fastest & average journey time, trains per day, distance, price-from, operators). The summary fetch retries with backoff on transient 429/500s before giving up. To increase the chance of full per-journey fares (price per train, exact times), enable the optional **Apify proxy** — it is engaged automatically only when a block is detected (no extra cost on direct traffic).
- The fallback record is marked `recordType: "journeySummary"`; full per-journey records are `recordType: "journey"`.
- Season-ticket filtering (`ticketType: "Season"`) only keeps journeys whose fare class is explicitly detected as seasonal — Trainline rarely exposes it per journey, so this filter may legitimately yield zero records.
- Trainline requires a valid future travel date; past dates are clamped to today + 7 days.
- Origin and destination resolving to the same station return 0 records (Trainline serves no data for identical stations) with a clear status message.
- The `train-times` summary pages are locale-independent — the `locale` input affects the station autocomplete and results page, not the summary URL (localized prefixes return 404).

### Output

#### Per journey (`recordType: "journey"`)

- `origin`, `destination` — resolved station names
- `departureTime`, `arrivalTime` — `HH:MM`
- `departureDate` — `YYYY-MM-DD`
- `durationMinutes`, `changes`
- `operator` — e.g. `Avanti West Coast`
- `price`, `currency` — ISO 4217 (`GBP`, `EUR`, …)
- `trainId`, `ticketType`, `fareClass`
- `sourceUrl`, `scrapedAt`, `recordType`

#### Per journey summary (`recordType: "journeySummary"`)

- `fromStation`, `toStation`, `fromSlug`, `toSlug`
- `firstTrain`, `lastTrain` — first/last departure times of the day
- `fastestJourneyMinutes`, `averageJourneyMinutes`
- `frequencyPerDay`, `distanceMiles`, `distanceKm`
- `directTrainsOnly`, `priceFrom`, `currency`
- `operators[]`
- `sourceUrl`, `scrapedAt`, `recordType`

#### Per station (`recordType: "station"`)

- `stationId`, `stationUrn`, `name`, `shortName` (e.g. `EUS`), `countryCode`
- `latitude`, `longitude`, `locationType`, `timezone`, `defaultLanguage`
- `parentName`, `subtitle`, `attributes[]`, `connections[]`, `matchScore`
- `sourceUrl` — UK stations link to their `/stations/<slug>` page; other stations link to the public locations-search endpoint that produced them

#### Per popular route (`recordType: "popularRoute"`)

- `originName`, `destinationName`, `priceFrom`, `currency`
- `durationMinutes`, `trainTimesPath`, `trainTimesUrl`, `isReverse`
- `sourceUrl`, `scrapedAt`, `recordType`

### Input

| Field | Type | Default | Description |
|---|---|---|---|
| `mode` | string | `search` | `search` / `stationLookup` / `popularRoutes` |
| `originStation` | string | `London Euston` | Departure station or city (mode=search) |
| `destinationStation` | string | `Birmingham New Street` | Arrival station or city (mode=search) |
| `stationQuery` | string | – | Station name to look up (mode=stationLookup) |
| `travelDate` | date | today + 7 days | Journey date `YYYY-MM-DD` (mode=search) |
| `departAfter` | string | – | Only journeys departing at/after `HH:MM` |
| `arriveBy` | string | – | Only journeys arriving at/before `HH:MM` |
| `ticketType` | string | – | `Standard` / `First` / `Season` |
| `maxPrice` | int | – | Drop records priced above this |
| `locale` | string | `en-gb` | Site locale (18 options) |
| `currency` | string | `GBP` | ISO 4217 currency code (24 options) |
| `maxItems` | int | `50` | Hard cap (1–200) |
| `proxyConfiguration` | object | off | Optional Apify proxy, engaged automatically on block |

#### Example: journey search

```json
{
  "mode": "search",
  "originStation": "London Euston",
  "destinationStation": "Birmingham New Street",
  "travelDate": "2026-09-10",
  "departAfter": "07:00",
  "maxItems": 20
}
```

#### Example: depart-after with filters

```json
{
  "mode": "search",
  "originStation": "Manchester Piccadilly",
  "destinationStation": "London Euston",
  "departAfter": "08:30",
  "arriveBy": "13:00",
  "ticketType": "Standard",
  "maxPrice": 60,
  "currency": "GBP"
}
```

#### Example: station lookup

```json
{
  "mode": "stationLookup",
  "stationQuery": "Birmingham"
}
```

#### Example: popular routes

```json
{
  "mode": "popularRoutes"
}
```

### Use cases

- **Rail price monitoring** — track "from" prices on popular UK/EU corridors
- **Journey planning data** — first/last trains, frequencies and durations for route research
- **Station reference data** — code, coordinates and connection lookups
- **Competitive intelligence** — corridor-level pricing intelligence for transport startups
- **Content enrichment** — route-level facts (distance, average time, operators) for travel sites

### FAQ

**What is the data source?** Trainline (www.thetrainline.com), a UK/EU train & bus fare metasearch platform. This actor is a third-party tool and is not affiliated with or endorsed by Trainline.

**Why did I get `journeySummary` records instead of `journey` records?** Trainline's fare engine is protected by DataDome bot detection. When it challenges automated traffic, the actor automatically emits the route-summary record (server-rendered, always accessible) so you still get real data. Enable the optional proxy for a better chance at full per-journey fares.

**Do I need an account or cookies?** No. Everything this actor reads is public.

**Are past dates allowed?** No — Trainline only serves current/future journeys. Past dates are clamped to today + 7 days.

**What currencies can I get?** Prices are returned in the currency you select (24 ISO 4217 codes available). The `currency` field on every record is an ISO 4217 code.

**Why are some fields missing?** Empty fields are omitted by design. For example, not every journey card shows a `trainId`, and not every route page lists a `priceFrom`.

**Is this free to run?** The actor uses the free Playwright base image. The optional proxy is only used when a block is detected, so most runs cost nothing extra.

**How fresh is the data?** Live. Journey and route pages are fetched at run time.

# Actor input Schema

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

What to fetch.

## `originStation` (type: `string`):

Departure station or city, e.g. `London Euston`, `Paris`, `Manchester Piccadilly` (mode=search).

## `destinationStation` (type: `string`):

Arrival station or city (mode=search).

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

Free-text station name, e.g. `London`, `Birmingham` — returns matching stations with codes, coordinates and connections.

## `travelDate` (type: `string`):

Journey date in `YYYY-MM-DD` (mode=search). Defaults to today + 7 days when empty or in the past.

## `departAfter` (type: `string`):

Only emit journeys departing at or after this time, `HH:MM` (mode=search).

## `arriveBy` (type: `string`):

Only emit journeys arriving at or before this time, `HH:MM` (mode=search).

## `ticketType` (type: `string`):

Fare class to keep: `Standard`, `First` or `Season` (mode=search). Journeys without a detectable class pass through.

## `maxPrice` (type: `integer`):

Drop records with a price above this amount (mode=search).

## `locale` (type: `string`):

Site locale used for station search and route pages.

## `currency` (type: `string`):

Currency code passed to the results page, e.g. `GBP`, `EUR`.

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

Hard cap on emitted records.

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

Optional Apify proxy. Engaged automatically only when the source blocks direct requests (403/429).

## Actor input object example

```json
{
  "mode": "search",
  "originStation": "London Euston",
  "destinationStation": "Birmingham New Street",
  "travelDate": "",
  "locale": "en-gb",
  "currency": "GBP",
  "maxItems": 10,
  "proxyConfiguration": {
    "useApifyProxy": false
  }
}
```

# Actor output Schema

## `journeys` (type: `string`):

Dataset containing all scraped Trainline journey, journey summary, station and popular route records.

# 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": "search",
    "originStation": "London Euston",
    "destinationStation": "Birmingham New Street",
    "locale": "en-gb",
    "currency": "GBP",
    "maxItems": 10,
    "proxyConfiguration": {
        "useApifyProxy": false
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("crawlerbros/trainline-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": "search",
    "originStation": "London Euston",
    "destinationStation": "Birmingham New Street",
    "locale": "en-gb",
    "currency": "GBP",
    "maxItems": 10,
    "proxyConfiguration": { "useApifyProxy": False },
}

# Run the Actor and wait for it to finish
run = client.actor("crawlerbros/trainline-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": "search",
  "originStation": "London Euston",
  "destinationStation": "Birmingham New Street",
  "locale": "en-gb",
  "currency": "GBP",
  "maxItems": 10,
  "proxyConfiguration": {
    "useApifyProxy": false
  }
}' |
apify call crawlerbros/trainline-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,crawlerbros/trainline-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/Pf4F5GCXbv6j4unbu/builds/qWuOjfhbwnuryY0Vz/openapi.json
