# Zagame Automotive Inventory Scraper (`rithvikc/zagame-automotive-inventory-scraper`) Actor

Scrape a live list of zagame automotive inventory

- **URL**: https://apify.com/rithvikc/zagame-automotive-inventory-scraper.md
- **Developed by:** [Rithvik Chand](https://apify.com/rithvikc) (community)
- **Categories:** Developer tools, Lead generation, E-commerce
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$10.00 / 1,000 cars

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

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

## Zagame Automotive Scraper

A comprehensive web scraper for [Zagame Automotive](https://www.zag.com.au/stock) that tracks vehicle inventory and maintains historical data in Airtable. Built for deployment on Apify.

### Features

- 🚗 **Complete Vehicle Data Extraction**: Scrapes all vehicle listings including make, model, year, price, kilometers, condition, and more
- 📊 **Airtable Integration**: Automatically updates Airtable database with current inventory
- 📈 **Historical Tracking**: Maintains historical data for price and availability changes
- 🔄 **Smart Updates**: Only updates records when significant changes are detected
- 🤖 **Apify Ready**: Fully configured for deployment on Apify platform
- 🔍 **Robust Scraping**: Handles pagination, retries, and various website layouts
- 📋 **Detailed Logging**: Comprehensive logging for monitoring and debugging

### Vehicle Data Captured

Each vehicle record includes:

- **Basic Info**: Title, Make, Model, Year, Variant
- **Pricing**: Price (numerical), Price Text (original format)
- **Details**: Kilometers, Condition (New/Used/Demo), Fuel Type, Body Type
- **Location**: Dealer/Branch information
- **Links**: Direct vehicle URL, Image URLs
- **Tracking**: Unique ID, Last Seen timestamp, Active status
- **History**: Scraped timestamp, historical changes

### Setup Instructions

#### 1. Airtable Setup

1. Create a new Airtable base or use an existing one
2. Create a table called "Vehicles" with the following fields:

| Field Name | Field Type | Description |
|------------|------------|-------------|
| Unique ID | Single line text | Primary key for vehicles |
| Title | Single line text | Full vehicle title |
| Year | Number | Vehicle year |
| Make | Single line text | Vehicle manufacturer |
| Model | Single line text | Vehicle model |
| Variant | Single line text | Specific variant/trim |
| Price | Number | Numerical price value |
| Price Text | Single line text | Original price text |
| Kilometers | Number | Odometer reading |
| Kilometers Text | Single line text | Original km text |
| Condition | Single select | New, Used, Demo |
| Fuel Type | Single line text | Petrol, Electric, etc. |
| Body Type | Single line text | Sedan, Hatch, SUV, etc. |
| Dealer | Single line text | Selling dealer |
| Vehicle URL | URL | Link to vehicle page |
| Images | Long text | Comma-separated image URLs |
| Scraped At | Date | When first scraped |
| Last Seen | Date | Last seen timestamp |
| Is Active | Checkbox | Currently available |
| Raw Text | Long text | Raw extracted text |

3. Optional: Create a "Vehicles_History" table for historical tracking with similar fields plus "Snapshot Date"

4. Get your Airtable API key from <https://airtable.com/create/tokens>

5. Get your Base ID from the Airtable API documentation page

#### 2. Apify Deployment

##### Option A: Deploy via GitHub (Recommended)

1. Fork or clone this repository
2. Push to your GitHub repository
3. In Apify Console:
   - Create new Actor
   - Connect to your GitHub repository
   - Set build settings to use this repository
   - Configure input schema (automatically detected)

##### Option B: Manual Upload

1. Zip the entire project
2. Upload to Apify Console
3. Configure as Node.js + Playwright actor

#### 3. Configuration

When running the actor, provide the following input:

```json
{
  "airtableApiKey": "your_airtable_api_key",
  "airtableBaseId": "your_base_id",
  "airtableTableName": "Vehicles",
  "maxPages": 0,
  "trackHistory": true,
  "runInterval": 24
}
```

##### Input Parameters

- **airtableApiKey** (required): Your Airtable API key
- **airtableBaseId** (required): Your Airtable base ID
- **airtableTableName** (optional): Table name (default: "Vehicles")
- **maxPages** (optional): Maximum pages to scrape (0 = all pages)
- **trackHistory** (optional): Enable historical tracking (default: true)
- **runInterval** (optional): How often to run in hours (default: 24)

### Local Development

#### Prerequisites

- Node.js 18+
- npm or yarn

#### Installation

```bash
## Clone the repository
git clone <your-repo-url>
cd zag-scraper

## Install dependencies
npm install

## Set environment variables (optional for local testing)
export AIRTABLE_API_KEY=your_api_key
export AIRTABLE_BASE_ID=your_base_id
```

#### Running Locally

```bash
## Run the scraper
npm start

## Run with development settings
npm run dev
```

#### Testing

```bash
## Run tests
npm test
```

### Architecture

```
src/
├── main.js                 # Entry point and orchestration
├── scrapers/
│   └── vehicleScraper.js   # Main scraping logic
├── services/
│   └── airtableManager.js  # Airtable operations
└── utils/
    ├── logger.js           # Logging utilities
    └── helpers.js          # Data processing helpers
```

### Key Components

#### VehicleScraper

- Handles navigation and pagination
- Extracts vehicle data from listings
- Processes and cleans scraped data
- Generates unique identifiers

#### AirtableManager

- Manages Airtable connections
- Handles batch operations (create/update)
- Tracks historical changes
- Calculates inventory statistics

#### Data Processing

- Price extraction and normalization
- Kilometer parsing
- Make/model recognition
- Text sanitization

### Monitoring & Logging

The scraper provides detailed logging for:

- Scraping progress (pages, vehicles found)
- Airtable operations (creates, updates)
- Error handling and retries
- Performance metrics

### Error Handling

- **Network Issues**: Automatic retries with exponential backoff
- **Rate Limits**: Built-in delays between requests
- **Data Validation**: Handles missing or malformed data gracefully
- **Airtable Limits**: Batch operations with size limits

### Scheduling

#### Apify Scheduler

Set up recurring runs in Apify Console:

- **Recommended**: Every 6-12 hours for active inventory tracking
- **Minimum**: Daily for basic inventory updates
- **High Frequency**: Every 2-4 hours for time-sensitive tracking

#### Custom Scheduling

The scraper can be configured with different intervals based on your needs:

- **Real Estate Mode**: Every 4-6 hours
- **Standard Mode**: Every 12-24 hours
- **Archive Mode**: Weekly for historical data

### Data Analysis

The Airtable database enables powerful analysis:

- Price trend tracking
- Inventory turnover rates
- Popular models and makes
- Dealer performance
- Market insights

### Troubleshooting

#### Common Issues

1. **No vehicles found**: Website structure may have changed
2. **Airtable connection fails**: Check API key and base ID
3. **Rate limit exceeded**: Increase delays between requests
4. **Memory issues**: Reduce batch sizes or page limits

#### Debug Mode

Enable detailed logging by setting the log level:

```javascript
log.setLevel('DEBUG');
```

### Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Submit a pull request

### License

MIT License - see LICENSE file for details

### Support

For issues and questions:

1. Check the troubleshooting section
2. Review Apify logs for error details
3. Verify Airtable configuration
4. Test with smaller page limits first

### Changelog

#### v1.0.0

- Initial release
- Full vehicle data extraction
- Airtable integration
- Historical tracking
- Apify deployment ready

# Actor input Schema

## `airtableApiKey` (type: `string`):

Your Airtable API key for authentication

## `airtableBaseId` (type: `string`):

The ID of your Airtable base (starts with 'app')

## `airtableTableName` (type: `string`):

Name of the table to store vehicle data

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

Maximum number of pages to scrape (0 = unlimited). Use with caution - unlimited scraping may timeout on free tier.

## `maxRunTimeMinutes` (type: `integer`):

Maximum time the scraper should run before stopping (recommended: 25 for free tier, 55 for paid)

## `trackHistory` (type: `boolean`):

Whether to save historical snapshots of vehicle data

## `runInterval` (type: `integer`):

How often to run the scraper automatically (in hours)

## Actor input object example

```json
{
  "airtableTableName": "Vehicles",
  "maxPages": 0,
  "maxRunTimeMinutes": 25,
  "trackHistory": true,
  "runInterval": 24
}
```

# 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("rithvikc/zagame-automotive-inventory-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("rithvikc/zagame-automotive-inventory-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 rithvikc/zagame-automotive-inventory-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,rithvikc/zagame-automotive-inventory-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/ufszf3ivC7olc5kjW/builds/o3OrctESjbRmu3yam/openapi.json
