# Hacker News Scraper & API - Export Stories, Comments, Data (`fresh_cliff/hackernews-scraper`) Actor

Extract top stories, trending posts, points, comments & authors from Hacker News front page. Real-time data export to JSON/CSV. Monitor tech trends, analyze viral content, track HN activity. Fast Playwright scraper.

- **URL**: https://apify.com/fresh_cliff/hackernews-scraper.md
- **Developed by:** [Brennan Crawford](https://apify.com/fresh_cliff) (community)
- **Categories:** News, Automation, Developer tools
- **Features:** Full permissions
- **Stats:** 6 total users, 0 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.50005 / actor start

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?

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

## Hacker News Scraper for Apify

A production-ready Apify actor that scrapes stories from Hacker News front page using Playwright.

### 🚀 Features

- Scrapes Hacker News front page stories
- Extracts comprehensive story data:
  - Title and URL
  - Points (upvotes)
  - Author username
  - Number of comments
  - Time posted
  - Story rank
  - Hacker News discussion URL
- Configurable number of stories to scrape
- Option to include/exclude job posts
- Built with Playwright for reliable scraping
- Production-ready for Apify platform

### 📁 Project Structure

```
hackernews-scraper/
├── .actor/
│   ├── actor.json              # Actor metadata and configuration
│   └── dataset_schema.json     # Output data schema
├── apify_actor.py              # Main actor entry point
├── hackernews_scraper.py       # Core scraper implementation
├── Dockerfile                  # Docker configuration for Apify
├── requirements.txt            # Python dependencies
├── INPUT_SCHEMA.json           # Input configuration schema
└── README.md                   # This file
```

### 🔧 Local Testing

#### Prerequisites

- Python 3.11+
- pip

#### Installation

1. Install dependencies:

```bash
pip install -r requirements.txt
```

2. Install Playwright browsers:

```bash
playwright install chromium
```

3. Test the scraper locally:

```bash
python hackernews_scraper.py
```

### 🌐 Deploy to Apify

#### Prerequisites

1. [Create an Apify account](https://console.apify.com/sign-up)
2. Install Apify CLI: `npm install -g apify-cli`
3. Login: `apify login`

#### Deployment Steps

1. **Navigate to project directory:**

```bash
cd hackernews-scraper
```

2. **Deploy to Apify:**

```bash
apify push
```

3. **Access your actor** at [Apify Console](https://console.apify.com/actors)

#### Running on Apify

1. Navigate to your actor in the Apify Console
2. Click "Run"
3. Configure input options (optional)
4. Click "Start" to run the actor
5. View results in the "Dataset" tab

### ⚙️ Input Configuration

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `maxStories` | integer | 30 | Maximum number of stories to scrape (1-100) |
| `includeJobPosts` | boolean | false | Include "Who is hiring?" job posts |

#### Example Input

```json
{
  "maxStories": 30,
  "includeJobPosts": false
}
```

### 📊 Output Format

Each story is returned as a JSON object with the following structure:

```json
{
  "rank": 1,
  "title": "Show HN: I built a tool for...",
  "url": "https://example.com/article",
  "points": 342,
  "author": "username",
  "comments": 127,
  "timeAgo": "2024-01-15T10:30:00.000Z",
  "hackerNewsUrl": "https://news.ycombinator.com/item?id=12345678"
}
```

#### Output Fields

| Field | Type | Description |
|-------|------|-------------|
| `rank` | number | Story position on front page |
| `title` | string | Story title |
| `url` | string | Link to the story/article |
| `points` | number | Number of upvotes |
| `author` | string | Username who posted the story |
| `comments` | number | Number of comments |
| `timeAgo` | string | Timestamp when story was posted |
| `hackerNewsUrl` | string | URL to Hacker News discussion |

### 🛠️ Built With

- **Python 3.11** - Programming language
- **Playwright** - Browser automation
- **Apify SDK** - Actor framework
- Following Apify best practices and patterns

### 📝 Use Cases

- Monitor trending tech stories
- Track specific topics on HN
- Build custom HN readers/aggregators
- Research what content performs well
- Create HN analytics dashboards

### 🔒 Rate Limiting

The scraper is designed to be respectful of Hacker News:

- Single page load per run
- No aggressive pagination
- Configurable limits on stories scraped

### 📄 License

This actor is provided as-is for use on the Apify platform.

### 🤝 Support

For issues or questions:

- Check the [Apify documentation](https://docs.apify.com)
- Open an issue in the repository
- Contact via Apify platform

***

**Ready to deploy in under 10 minutes! 🎉**

# Actor input Schema

## `maxStories` (type: `integer`):

Maximum number of stories to scrape from the front page (default: 30)

## `includeJobPosts` (type: `boolean`):

Whether to include 'Who is hiring?' job posts

## Actor input object example

```json
{
  "maxStories": 30,
  "includeJobPosts": false
}
```

# 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("fresh_cliff/hackernews-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("fresh_cliff/hackernews-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 fresh_cliff/hackernews-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,fresh_cliff/hackernews-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/kS9CgKnm24rCTxVVD/builds/813ir0WUJflhrP4DT/openapi.json
