# Intelligent Website Crawler (`happitap/intelligent-website-crawler`) Actor

- **URL**: https://apify.com/happitap/intelligent-website-crawler.md
- **Developed by:** [HappiTap](https://apify.com/happitap) (community)
- **Categories:** Automation
- **Stats:** 2 total users, 1 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

Learn more: https://docs.apify.com/platform/actors/running/actors-in-store#pay-per-usage

## 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

## AI-Enhanced Website Crawler

An intelligent website crawler that combines advanced crawling capabilities with AI-powered page classification, pattern detection, and content extraction. This enhanced version supports all the features of Apify's Website Crawler plus intelligent AI processing to minimize API usage and maximize data extraction efficiency.

### 🚀 Key Features

#### Advanced Crawling Capabilities

- **Multiple Crawler Types**: Supports Playwright (adaptive, Chrome, Firefox) and Puppeteer
- **Smart Content Extraction**: Comprehensive data extraction including metadata, markdown, text, screenshots
- **Dynamic Content Handling**: Handles JavaScript-rendered content, infinite scroll, and expandable elements
- **Sitemap Support**: Automatically discovers and processes XML sitemaps
- **Proxy Support**: Built-in Apify Proxy integration with rotation
- **Media Blocking**: Optional blocking of images/videos for faster crawling

#### AI-Powered Intelligence

- **Automatic Page Classification**: AI identifies page types (product, category, service, contact, blog, FAQ, etc.)
- **Pattern Learning**: Learns page patterns to reduce AI API calls for similar pages
- **Smart Content Processing**: Context-aware content extraction based on page type
- **Token Optimization**: Aggressive content pruning to minimize AI API costs
- **Caching System**: Reuses learned patterns for similar page structures

#### Comprehensive Output

- **Multiple Formats**: HTML, Markdown, clean text, structured metadata
- **Screenshots**: Optional full-page screenshots with cloud storage URLs
- **Performance Metrics**: Load times, content metrics, accessibility info
- **AI Insights**: Page classification, extracted patterns, processed content
- **Link Analysis**: Internal/external link discovery with metadata

### 📋 Input Configuration

#### Basic Crawler Settings

```json
{
  "startUrls": [
    {
      "url": "https://example.com",
      "method": "GET"
    }
  ],
  "crawlerType": "playwright:adaptive",
  "maxCrawlPages": 100,
  "maxCrawlDepth": 3,
  "maxConcurrency": 10
}
```

#### AI Configuration

```json
{
  "enableAI": true,
  "aiModel": "gpt-3.5-turbo",
  "enablePatternLearning": true,
  "patternSimilarityThreshold": 0.8,
  "maxAICallsPerRun": 50,
  "taskType": "auto"
}
```

#### Content Processing

```json
{
  "saveMarkdown": true,
  "saveHtml": false,
  "saveScreenshots": false,
  "blockMedia": true,
  "removeCookieWarnings": true,
  "dynamicContentWaitSecs": 10
}
```

### 🎯 Task Types

- **auto**: AI automatically detects the best processing approach
- **summarize**: Creates comprehensive content summaries
- **extractProducts**: Extracts product information (name, price, features, specs)
- **extractServices**: Extracts service offerings and descriptions
- **extractFAQs**: Extracts question-answer pairs and help content
- **extractContacts**: Extracts contact information and business details

### 📊 Output Format

```json
{
  "url": "https://example.com/product/123",
  "timestamp": "2024-01-15T10:30:00Z",
  "crawlTime": 2500,
  "metadata": {
    "title": "Product Name - Company",
    "description": "Product description from meta tags",
    "ogTitle": "Open Graph title",
    "schema": ["JSON-LD structured data"]
  },
  "content": {
    "html": "<html>...</html>",
    "markdown": "# Product Name\n\nProduct description...",
    "text": "Clean text content",
    "title": "Product Name",
    "headings": [
      {"level": 1, "text": "Product Name", "id": "heading-0"}
    ],
    "links": [
      {"url": "https://example.com/related", "text": "Related Product"}
    ],
    "images": [
      {"url": "https://example.com/image.jpg", "alt": "Product image"}
    ]
  },
  "screenshots": {
    "key": "screenshot-1234567890.png",
    "url": "https://api.apify.com/v2/key-value-stores/.../screenshot-1234567890.png"
  },
  "ai": {
    "classification": {
      "type": "product",
      "confidence": 0.95,
      "reasoning": "Page contains product information with pricing and specifications"
    },
    "patterns": {
      "selectors": {
        "title": ".product-title",
        "price": ".price",
        "description": ".product-description"
      },
      "confidence": 0.85
    },
    "processedContent": {
      "processed": true,
      "content": "Structured extracted data based on page type"
    }
  },
  "performance": {
    "loadTime": 1200,
    "domContentLoaded": 800,
    "firstPaint": 600
  },
  "accessibility": {
    "hasAltTexts": 5,
    "missingAltTexts": 1,
    "headingStructure": ["h1", "h2", "h2", "h3"]
  }
}
```

### 🧠 AI Features in Detail

#### Page Classification

The AI automatically identifies page types:

- **Product pages**: Individual product listings with specs and pricing
- **Category pages**: Product category or listing pages
- **Service pages**: Service descriptions and offerings
- **Contact pages**: Contact info, about us, company details
- **Blog pages**: Articles, news, blog posts
- **FAQ pages**: Help, support, and FAQ content
- **Home pages**: Landing pages and homepages

#### Pattern Learning

- Analyzes page structure and identifies data extraction patterns
- Caches successful patterns for reuse on similar pages
- Reduces AI API calls by up to 80% on sites with consistent structure
- Learns CSS selectors for key data elements

#### Smart Content Processing

- Adapts processing strategy based on detected page type
- Extracts relevant structured data automatically
- Minimizes token usage through intelligent content pruning
- Provides confidence scores for all AI decisions

### 🔧 Advanced Configuration

#### Extract Services with Internal Link Following

```json
{
  "startUrls": [
    { "url": "https://example.com" }
  ],
  "taskType": "extractServices",
  "followInternalLinks": true,
  "maxDepth": 2
}
```

#### Extract Products from Multiple URLs

```json
{
  "startUrls": [
    { "url": "https://shop1.com" },
    { "url": "https://shop2.com" }
  ],
  "taskType": "extractProducts"
}
```

### How It Works

1. **Content Extraction**: Uses Puppeteer to load pages and Cheerio to extract clean content
2. **Intelligent Processing**: LangChain processes content based on the specified task type
3. **Structured Output**: Returns processed content with metadata and original URL
4. **Optional Crawling**: Can follow internal links to gather more comprehensive data

### Installation

1. Clone this repository
2. Install dependencies: `npm install`
3. Set your `OPENAI_API_KEY` environment variable
4. Run the actor: `npm start`

### Development

- `npm start` - Run the actor
- `npm run format` - Format code with Prettier
- `npm run lint` - Run ESLint
- `npm run lint:fix` - Fix ESLint issues

### Architecture

- `src/main.js` - Main entry point and input validation
- `src/routes.js` - Request routing
- `src/handlers/websiteScraper.js` - Main scraping logic
- `src/services/langchainService.js` - LangChain integration and task processing
- `src/puppeteerLauncher.js` - Puppeteer browser configuration

# Actor input Schema

## `startUrls` (type: `array`):

Array of URLs to scrape. Each URL should be an object with a 'url' property and optional 'method'.

## `crawlerType` (type: `string`):

Type of crawler to use

## `maxCrawlPages` (type: `integer`):

Maximum number of pages to crawl

## `maxCrawlDepth` (type: `integer`):

Maximum depth to crawl from start URLs

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

Maximum concurrent browser instances. Higher values = faster crawling but more memory usage. Pattern learning is thread-safe for high concurrency.

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

Maximum number of retries for failed requests

## `requestTimeoutSecs` (type: `integer`):

Timeout for each request in seconds

## `dynamicContentWaitSecs` (type: `integer`):

Time to wait for dynamic content to load

## `includeUrlGlobs` (type: `array`):

Glob patterns for URLs to include

## `excludeUrlGlobs` (type: `array`):

Glob patterns for URLs to exclude

## `useSitemaps` (type: `boolean`):

Whether to automatically discover and use sitemaps

## `aggressivePrune` (type: `boolean`):

More aggressively prune content to reduce token usage

## `blockMedia` (type: `boolean`):

Block images, videos, and other media to speed up crawling

## `saveMarkdown` (type: `boolean`):

Save page content as markdown

## `saveHtml` (type: `boolean`):

Save raw HTML content

## `saveScreenshots` (type: `boolean`):

Take and save screenshots of pages

## `removeElementsCssSelector` (type: `string`):

CSS selector for elements to remove before processing

## `clickElementsCssSelector` (type: `string`):

CSS selector for elements to click (e.g., expand buttons)

## `waitForSelector` (type: `string`):

CSS selector to wait for before processing page

## `maxScrollHeightPixels` (type: `integer`):

Maximum height to scroll for infinite scroll pages

## `readableTextCharThreshold` (type: `integer`):

Minimum characters required for content to be considered readable

## `removeCookieWarnings` (type: `boolean`):

Automatically remove cookie consent banners

## `respectRobotsTxtFile` (type: `boolean`):

Whether to respect robots.txt file

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

Proxy settings for requests

## `enableAI` (type: `boolean`):

Enable AI-powered page classification, smart pattern learning, and intelligent content extraction. Highly recommended for structured data extraction.

## `aiModel` (type: `string`):

OpenAI model for AI processing. gpt-3.5-turbo is cost-effective for most use cases. Use gpt-4 for complex content extraction.

## `enablePatternLearning` (type: `boolean`):

Enable smart DOM pattern learning to dramatically reduce AI API costs (90-99% savings). Learns page structures once and reuses for similar pages. Essential for large sites.

## `patternSimilarityThreshold` (type: `number`):

Threshold for considering pages similar (0-1)

## `maxAICallsPerRun` (type: `integer`):

Maximum AI API calls allowed per run. With pattern learning, you can crawl thousands of pages with just 10-50 AI calls. Start conservative and increase as needed.

## `taskType` (type: `string`):

Primary task for content processing (auto-detection recommended)

## `useSitemap` (type: `boolean`):

Automatically discover pages from website sitemap.xml. Combines with Start URLs for comprehensive crawling.

## `sitemapUrls` (type: `array`):

URLs of sitemaps to crawl

## `sitemapMaxPages` (type: `integer`):

Maximum number of pages to extract from sitemaps. Use to limit crawl scope for large sites.

## `sitemapFilterPatterns` (type: `array`):

Filter sitemap URLs by patterns (e.g., '/product/', '/category/'). Include patterns you want, exclude with '!' prefix.

## Actor input object example

```json
{
  "startUrls": [
    {
      "url": "https://example.com",
      "method": "GET"
    }
  ],
  "crawlerType": "playwright:adaptive",
  "maxCrawlPages": 100,
  "maxCrawlDepth": 3,
  "maxConcurrency": 50,
  "maxRequestRetries": 3,
  "requestTimeoutSecs": 60,
  "dynamicContentWaitSecs": 10,
  "includeUrlGlobs": [],
  "excludeUrlGlobs": [],
  "useSitemaps": true,
  "aggressivePrune": false,
  "blockMedia": true,
  "saveMarkdown": true,
  "saveHtml": false,
  "saveScreenshots": false,
  "removeElementsCssSelector": "nav, footer, script, style, noscript, svg, img[src^='data:'], [role=\"alert\"], [role=\"banner\"], [role=\"dialog\"], [role=\"alertdialog\"], [role=\"region\"][aria-label*=\"skip\" i], [aria-modal=\"true\"]",
  "clickElementsCssSelector": "[aria-expanded=\"false\"]",
  "waitForSelector": "",
  "maxScrollHeightPixels": 5000,
  "readableTextCharThreshold": 100,
  "removeCookieWarnings": true,
  "respectRobotsTxtFile": true,
  "proxyConfiguration": {
    "useApifyProxy": true
  },
  "enableAI": true,
  "aiModel": "gpt-3.5-turbo",
  "enablePatternLearning": true,
  "patternSimilarityThreshold": 0.8,
  "maxAICallsPerRun": 50,
  "taskType": "auto",
  "useSitemap": false,
  "sitemapMaxPages": 1000,
  "sitemapFilterPatterns": []
}
```

# Actor output Schema

## `results` (type: `string`):

Extracted data items stored in the default dataset.

# 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 = {
    "startUrls": [
        {
            "url": "https://example.com",
            "method": "GET"
        }
    ],
    "proxyConfiguration": {
        "useApifyProxy": true
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("happitap/intelligent-website-crawler").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 = {
    "startUrls": [{
            "url": "https://example.com",
            "method": "GET",
        }],
    "proxyConfiguration": { "useApifyProxy": True },
}

# Run the Actor and wait for it to finish
run = client.actor("happitap/intelligent-website-crawler").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 '{
  "startUrls": [
    {
      "url": "https://example.com",
      "method": "GET"
    }
  ],
  "proxyConfiguration": {
    "useApifyProxy": true
  }
}' |
apify call happitap/intelligent-website-crawler --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,happitap/intelligent-website-crawler"
        }
    }
}

```

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/i4ReaWIbTv0NHl2fC/builds/k0ivH0bXsxwUwu6Tq/openapi.json
