# AI-Powered Smart Web Scraper (`cloud9_ai/ai-web-scraper`) Actor

Intelligent content extraction from any website using Crawlee + AI. Auto-detects structure, adapts to layout changes, handles JavaScript rendering. No custom code needed. Extract articles, products, listings from 1000s of pages.

- **URL**: https://apify.com/cloud9\_ai/ai-web-scraper.md
- **Developed by:** [cloud9](https://apify.com/cloud9_ai) (community)
- **Categories:** AI, Automation
- **Stats:** 30 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $5.00 / 1,000 results

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?

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 Web Scraper

Extract AI-ready content from any website. Clean Markdown output, smart chunking for RAG/embeddings, and structured metadata — optimized for LLM data pipelines.

### Features

- **Clean Markdown Output** — Automatically removes navigation, ads, footers, sidebars, and cookie banners. Extracts only the main content.
- **Smart Chunking** — Paragraph-aware text splitting with configurable chunk size and overlap. Perfect for vector databases and embedding models.
- **Token Estimation** — Each chunk includes an estimated token count, compatible with OpenAI, Cohere, and other tokenizers.
- **Structured Metadata** — Extracts title, description, language, author, publish date, OG images, headings, links, and images.
- **Multi-page Crawling** — Follow links within the same domain with configurable depth. Process entire documentation sites or blogs.
- **Multiple Output Formats** — Markdown (default), plain text, or raw HTML.

### Use Cases

- **RAG Pipelines** — Feed clean, chunked content into retrieval-augmented generation systems
- **Vector Database Ingestion** — Ready-to-embed chunks for Pinecone, Weaviate, Qdrant, ChromaDB, Milvus
- **LLM Fine-tuning Data** — Extract structured training data from web sources
- **Knowledge Base Building** — Crawl documentation sites and create searchable knowledge bases
- **Content Analysis** — Extract and analyze web content at scale

### Input

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `urls` | string\[] | (required) | URLs to scrape |
| `maxPages` | integer | 10 | Maximum pages to crawl |
| `outputFormat` | string | "markdown" | Output format: "markdown", "text", or "html" |
| `chunkSize` | integer | 1000 | Target chunk size in tokens |
| `chunkOverlap` | integer | 100 | Overlap between chunks in tokens |
| `excludeSelectors` | string\[] | \[] | Additional CSS selectors to exclude |
| `includeLinks` | boolean | true | Include extracted links in metadata |
| `includeImages` | boolean | true | Include extracted images in metadata |
| `maxDepth` | integer | 0 | Crawl depth (0 = provided URLs only) |
| `respectRobotsTxt` | boolean | true | Respect robots.txt rules |

### Output

Each page produces a dataset item with:

```json
{
  "url": "https://example.com/page",
  "metadata": {
    "title": "Page Title",
    "description": "Meta description",
    "language": "en",
    "author": "Author Name",
    "publishedDate": "2025-01-15",
    "ogImage": "https://example.com/image.jpg",
    "headings": [{ "level": 1, "text": "Main Heading" }],
    "links": [{ "text": "Link Text", "href": "https://.../" }],
    "images": [{ "alt": "Image description", "src": "https://.../" }]
  },
  "content": "# Main Heading\n\nClean markdown content...",
  "chunks": [
    {
      "index": 0,
      "text": "First chunk of content...",
      "tokenEstimate": 245,
      "charCount": 980
    }
  ],
  "totalTokenEstimate": 1520,
  "scrapedAt": "2025-01-15T10:30:00.000Z"
}
```

### Integration Examples

#### Pinecone / Vector DB

```python
from apify_client import ApifyClient

client = ApifyClient("YOUR_API_TOKEN")
run = client.actor("your-username/ai-web-scraper").call(
    run_input={"urls": ["https://docs.example.com/"], "maxDepth": 2, "chunkSize": 512}
)

for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    for chunk in item["chunks"]:
        # Embed and upsert to your vector database
        embedding = embed(chunk["text"])
        index.upsert([(f"{item['url']}_{chunk['index']}", embedding, {
            "text": chunk["text"],
            "url": item["url"],
            "title": item["metadata"]["title"],
        })])
```

#### LangChain

```python
from langchain.document_loaders import ApifyDatasetLoader
from langchain.schema import Document

loader = ApifyDatasetLoader(
    dataset_id=run["defaultDatasetId"],
    dataset_mapping_function=lambda item: [
        Document(
            page_content=chunk["text"],
            metadata={"source": item["url"], "chunk_index": chunk["index"]},
        )
        for chunk in item["chunks"]
    ],
)
docs = loader.load()
```

### Chunk Size Recommendations

| Embedding Model | Recommended Chunk Size |
|----------------|----------------------|
| OpenAI text-embedding-3-small | 500–1000 |
| OpenAI text-embedding-3-large | 1000–2000 |
| Cohere embed-v3 | 256–512 |
| Sentence Transformers | 256–512 |
| Google Gecko | 500–1000 |

### Pricing

This actor uses pay-per-event pricing at approximately **$0.005 per page** processed.

### License

MIT

# Actor input Schema

## `urls` (type: `array`):

List of URLs to scrape. Each URL will be processed and its content extracted.

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

Maximum number of pages to crawl. Applies when maxDepth > 0 for multi-page crawling.

## `outputFormat` (type: `string`):

Format of the extracted content.

## `chunkSize` (type: `integer`):

Target size for each text chunk in estimated tokens. Ideal for embedding models (OpenAI: 8191, Cohere: 512).

## `chunkOverlap` (type: `integer`):

Number of overlapping tokens between consecutive chunks. Helps maintain context across chunk boundaries.

## `excludeSelectors` (type: `array`):

Additional CSS selectors to remove from the page before extraction. Nav, footer, ads are already excluded by default.

## `includeLinks` (type: `boolean`):

Extract all links from the page and include them in metadata.

## `includeImages` (type: `boolean`):

Extract all images from the page and include them in metadata.

## `maxDepth` (type: `integer`):

Maximum crawl depth. 0 = only the provided URLs, 1 = follow links one level deep, etc.

## `respectRobotsTxt` (type: `boolean`):

Whether to respect robots.txt rules. Recommended to keep enabled.

## Actor input object example

```json
{
  "urls": [
    "https://example.com/"
  ],
  "maxPages": 10,
  "outputFormat": "markdown",
  "chunkSize": 1000,
  "chunkOverlap": 100,
  "excludeSelectors": [],
  "includeLinks": true,
  "includeImages": true,
  "maxDepth": 0,
  "respectRobotsTxt": true
}
```

# 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 = {
    "urls": [
        "https://example.com/"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("cloud9_ai/ai-web-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 = { "urls": ["https://example.com/"] }

# Run the Actor and wait for it to finish
run = client.actor("cloud9_ai/ai-web-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 '{
  "urls": [
    "https://example.com/"
  ]
}' |
apify call cloud9_ai/ai-web-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,cloud9_ai/ai-web-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/sh29xOpPZXCbuy7E0/builds/PX1LdWXegiA5nQOS3/openapi.json
