# Refinery — HTML to LLM Text (Cut RAG Token Cost) (`larelabs/refinery-html-to-llm-cleaner`) Actor

HTML to LLM text cleaner for RAG pipelines. Strip scripts, nav & layout junk after Firecrawl or your fetch. BeautifulSoup-alternative speed. $0.002/page · 3 README demos in Console.

- **URL**: https://apify.com/larelabs/refinery-html-to-llm-cleaner.md
- **Developed by:** [Lare Labs](https://apify.com/larelabs) (community)
- **Categories:** AI, Developer tools, Agents
- **Stats:** 3 total users, 1 monthly users, 100.0% runs succeeded, 1 bookmarks
- **User rating**: No ratings yet

## Pricing

from $2.00 / 1,000 html extractions

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/platform/actors/running/actors-in-store#pay-per-event

## What's an Apify Actor?

Actors are a software tools running on the Apify platform, for all kinds of web data extraction and automation use cases.
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.

In JavaScript/TypeScript projects, use official [JavaScript/TypeScript client](https://docs.apify.com/api/client/js.md):

```bash
npm install apify-client
```

In Python projects, use official [Python client library](https://docs.apify.com/api/client/python.md):

```bash
pip install apify-client
```

In shell scripts, use [Apify CLI](https://docs.apify.com/cli/docs.md):

````bash
# MacOS / Linux
curl -fsSL https://apify.com/install-cli.sh | bash
# Windows
irm https://apify.com/install-cli.ps1 | iex
```bash

In AI frameworks, you might use the [Apify MCP server](https://docs.apify.com/platform/integrations/mcp.md).

If your project is in a different language, use 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

## Refinery — HTML to LLM text cleaner for RAG pipelines

**Apify Actor that cleans bloated HTML before chunking and embedding** — strip scripts, nav, ads, and layout junk from pages you already fetched.  
Pay **$0.002/page** · **~2–8ms** per page (Rust core, after your crawler runs).

[![Price](https://img.shields.io/badge/price-%240.002%2Fpage-blue)](https://apify.com/larelabs/refinery-html-to-llm-cleaner/pricing)
[![Speed](https://img.shields.io/badge/speed-2--8ms%2Fpage-brightgreen)]()

![Refinery pipeline: raw HTML to clean JSON for RAG](https://i.imgur.com/rKLRTc1.png)

---

### Reduce LLM token cost — HTML cleaner for RAG

![Token reduction: bloated HTML vs clean text after Refinery](https://i.imgur.com/RxmHFBz.png)

News-style homepages and heavy DOM pages often waste tokens on chrome. Refinery returns **main-body text** plus `word_count` so you can budget embeddings — **up to ~97% fewer estimated tokens** on bloated HTML (your mileage varies).

---

### Clean social feed HTML for chunking and embeddings

Scraped timelines and comment threads ship messy DOM — scripts, sidebars, widgets. Refinery keeps **post body text** and normalizes **@mentions** / **#hashtags** for RAG chunking without paying for layout noise.

![Social and feed HTML: mentions and hashtags preserved as clean text](https://i.imgur.com/C6fISu7.png)

Paste `raw_payload` from your scraper, or pass URLs if you already fetch HTML elsewhere.

---

### Apify Console output — clean text and word count

Run **Try actor** with the prefilled `example.com` URL — each dataset row includes `text`, `word_count`, and timing:

![Apify dataset output: clean text, word count, and timing](https://i.imgur.com/tZytWi2.png)

---

### Bulk HTML cleaning for crawl batches

Send **many URLs in one run** — each row gets `text`, `word_count`, and `processing_time_ms`. Ideal after a sitemap pass, Firecrawl export, or Apify crawler dataset.

![Bulk URL mode: many pages in, dataset rows out](https://i.imgur.com/GPYU1hT.png)

```json
{
  "urls": [
    "https://example.com",
    "https://www.bbc.com/news",
    "https://httpbin.org/html"
  ],
  "removeScripts": true,
  "removeStyles": true,
  "includeMetadata": true
}
````

***

### Who uses this HTML text extractor

- **RAG and agent builders** cutting OpenAI / Anthropic token spend on page HTML
- **Scrape pipelines** that already fetch HTML (Firecrawl, Crawl4AI, Playwright, Apify Web Scraper)
- **Teams** replacing per-worker BeautifulSoup with a fast **HTML parser API** on Apify

**Refinery is not a web crawler.** It is an HTML-to-text preprocessing step after fetch.

```
Your crawler → raw HTML → Refinery → clean text → chunk → embed → vector DB → LLM
```

***

### Try the HTML to LLM cleaner (3 demos)

**Demo 1** is prefilled in Console. Paste **Demo 2** or **Demo 3** to see different modes.

#### Demo 1 — Quick URL

```json
{
  "urls": ["https://example.com"],
  "removeScripts": true,
  "removeStyles": true,
  "includeMetadata": true
}
```

#### Demo 2 — Bloated news homepage

```json
{
  "urls": ["https://www.bbc.com/news"],
  "removeScripts": true,
  "removeStyles": true,
  "includeMetadata": true
}
```

#### Demo 3 — Paste HTML (middleware)

```json
{
  "raw_payload": "<html><head><script>gtag('event')</script></head><body><nav>Home · Pricing</nav><article><h1>Update</h1><p>Clean before embedding.</p></article></body></html>",
  "removeScripts": true,
  "removeStyles": true,
  "includeMetadata": true
}
```

***

### Output — text, word\_count, language, timing

```json
{
  "text": "Example Product Page\nEnterprise AI Infrastructure...",
  "language": "en",
  "word_count": 12,
  "content_type": "web",
  "processing_time_ms": 19.29,
  "success": true
}
```

| Field | Use it for |
|-------|------------|
| `text` | Chunking, embeddings, LLM context |
| `word_count` | Cost estimates |
| `processing_time_ms` | Latency monitoring |

***

### Firecrawl, Crawl4AI, and BeautifulSoup alternative

![Refinery in your stack: crawler, clean, vector DB, LLM](https://i.imgur.com/mBbhQwd.png)

| You already use… | Refinery's job |
|------------------|----------------|
| **Firecrawl**, **Crawl4AI** | Clean their HTML before chunking — fetch with them, **clean with Refinery** |
| **Apify Web Scraper**, Website Content Crawler | Clean the `html` field in your dataset |
| **BeautifulSoup** (self-hosted) | Same job, ~281× faster hot path in our benchmarks — pay per page on Apify instead of worker CPU |

***

### Pricing — HTML extraction on Apify

| Event | Cost |
|-------|------|
| HTML extraction | **$0.002** / page |
| ~1,000 pages | **~$2.05** |

***

### Integrate via Apify API (JavaScript and Python)

#### JavaScript

```javascript
import { ApifyClient } from 'apify-client';
const client = new ApifyClient({ token: process.env.APIFY_TOKEN });
const run = await client.actor('larelabs/refinery-html-to-llm-cleaner').call({
  urls: ['https://example.com'],
});
const { items } = await client.dataset(run.defaultDatasetId).listItems();
console.log(items[0].text, items[0].word_count);
```

#### Python

```python
from apify_client import ApifyClient
client = ApifyClient(os.environ["APIFY_TOKEN"])
run = client.actor("larelabs/refinery-html-to-llm-cleaner").call(
    run_input={"urls": ["https://example.com"]}
)
print(next(client.dataset(run["defaultDatasetId"]).iterate_items()))
```

***

### FAQ — HTML cleaning for LLM and RAG

#### Is Refinery a replacement for Firecrawl or Crawl4AI?

No. **Fetch with Firecrawl or Crawl4AI, then clean with Refinery.** Refinery does not crawl URLs on its own schedule — it strips noise from HTML you already have (or fetches URLs you pass in this run).

#### How do I reduce RAG token cost from bloated HTML?

Run Refinery on raw HTML **before** chunking and embedding. Use `word_count` in the output to estimate savings. Remove scripts, styles, nav, and footer chrome so embeddings only see article body text.

#### Is this a BeautifulSoup alternative for HTML text extraction?

Yes — same preprocessing job (HTML → clean text), implemented in **Rust** for low latency. Use it when you want a managed Apify step instead of BeautifulSoup on every worker.

#### Can I clean HTML after Apify Web Scraper or Website Content Crawler?

Yes. Pass each page's HTML via `raw_payload`, or pipe URLs from your crawl. Refinery returns plain text ready for chunking.

#### Does Refinery handle JavaScript SPAs?

Only if you pass **rendered HTML** from a browser crawler (Playwright, Puppeteer, Firecrawl). Refinery cleans DOM; it does not execute JavaScript.

#### Can Refinery scrape social feeds or X / Twitter?

No login or feed scraping. Pass saved timeline HTML via `raw_payload` — Refinery extracts post text and normalizes @mentions / #hashtags.

***

### Support — LareLabs

**LareLabs** · [Apify Store listing](https://apify.com/larelabs/refinery-html-to-llm-cleaner) · [Console](https://console.apify.com/organization/vTZ0XDFG4cZCNAdQl/actors/jOcx8jK2FdhZhoKrE)

***

*Rust core · Apify Actor · Update WebPs in `assets/store/`, upload PNGs to Imgur, edit `image_urls.json`, then run embed + sync scripts.*

# Actor input Schema

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

Fetch each URL and return clean text. Best for Demo 1 (example.com) or Demo 2 (bbc.com/news) from the README.

## `raw_payload` (type: `string`):

Paste raw HTML from your crawler. Use when you already have HTML on disk or in your pipeline (see README Demo 3).

## `removeScripts` (type: `boolean`):

Strip JavaScript and tracking scripts

## `removeStyles` (type: `boolean`):

Strip CSS and style tags

## `includeMetadata` (type: `boolean`):

Return language, word\_count, and processing\_time\_ms

## `extractMentions` (type: `boolean`):

Pull @mentions from social HTML

## `extractHashtags` (type: `boolean`):

Pull hashtags from social HTML

## Actor input object example

```json
{
  "urls": [
    "https://example.com"
  ],
  "raw_payload": "<html><head><script>gtag('event','page_view')</script><style>.nav,.footer{display:block}</style></head><body><nav>Home · Pricing · Login</nav><article><h1>Quarterly update</h1><p>We reduced embedding cost by cleaning HTML before chunking.</p></article><footer>© 2026 · Legal · Careers</footer></body></html>",
  "removeScripts": true,
  "removeStyles": true,
  "includeMetadata": true,
  "extractMentions": false,
  "extractHashtags": false
}
```

# Actor output Schema

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

No description

# 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"
    ],
    "raw_payload": "<html><head><script>gtag('event','page_view')</script><style>.nav,.footer{display:block}</style></head><body><nav>Home · Pricing · Login</nav><article><h1>Quarterly update</h1><p>We reduced embedding cost by cleaning HTML before chunking.</p></article><footer>© 2026 · Legal · Careers</footer></body></html>"
};

// Run the Actor and wait for it to finish
const run = await client.actor("larelabs/refinery-html-to-llm-cleaner").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"],
    "raw_payload": "<html><head><script>gtag('event','page_view')</script><style>.nav,.footer{display:block}</style></head><body><nav>Home · Pricing · Login</nav><article><h1>Quarterly update</h1><p>We reduced embedding cost by cleaning HTML before chunking.</p></article><footer>© 2026 · Legal · Careers</footer></body></html>",
}

# Run the Actor and wait for it to finish
run = client.actor("larelabs/refinery-html-to-llm-cleaner").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print("💾 Check your data here: https://console.apify.com/storage/datasets/" + run["defaultDatasetId"])
for item in client.dataset(run["defaultDatasetId"]).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"
  ],
  "raw_payload": "<html><head><script>gtag('\''event'\'','\''page_view'\'')</script><style>.nav,.footer{display:block}</style></head><body><nav>Home · Pricing · Login</nav><article><h1>Quarterly update</h1><p>We reduced embedding cost by cleaning HTML before chunking.</p></article><footer>© 2026 · Legal · Careers</footer></body></html>"
}' |
apify call larelabs/refinery-html-to-llm-cleaner --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=larelabs/refinery-html-to-llm-cleaner",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

```json
{
    "openapi": "3.0.1",
    "info": {
        "title": "Refinery — HTML to LLM Text (Cut RAG Token Cost)",
        "description": "HTML to LLM text cleaner for RAG pipelines. Strip scripts, nav & layout junk after Firecrawl or your fetch. BeautifulSoup-alternative speed. $0.002/page · 3 README demos in Console.",
        "version": "1.1",
        "x-build-id": "wfO39IIF6CCBD5MAy"
    },
    "servers": [
        {
            "url": "https://api.apify.com/v2"
        }
    ],
    "paths": {
        "/acts/larelabs~refinery-html-to-llm-cleaner/run-sync-get-dataset-items": {
            "post": {
                "operationId": "run-sync-get-dataset-items-larelabs-refinery-html-to-llm-cleaner",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for its completion, and returns Actor's dataset items in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        },
        "/acts/larelabs~refinery-html-to-llm-cleaner/runs": {
            "post": {
                "operationId": "runs-sync-larelabs-refinery-html-to-llm-cleaner",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor and returns information about the initiated run in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "$ref": "#/components/schemas/runsResponseSchema"
                                }
                            }
                        }
                    }
                }
            }
        },
        "/acts/larelabs~refinery-html-to-llm-cleaner/run-sync": {
            "post": {
                "operationId": "run-sync-larelabs-refinery-html-to-llm-cleaner",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for completion, and returns the OUTPUT from Key-value store in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        }
    },
    "components": {
        "schemas": {
            "inputSchema": {
                "type": "object",
                "properties": {
                    "urls": {
                        "title": "URLs to clean",
                        "type": "array",
                        "description": "Fetch each URL and return clean text. Best for Demo 1 (example.com) or Demo 2 (bbc.com/news) from the README.",
                        "items": {
                            "type": "string"
                        }
                    },
                    "raw_payload": {
                        "title": "HTML to clean (paste)",
                        "type": "string",
                        "description": "Paste raw HTML from your crawler. Use when you already have HTML on disk or in your pipeline (see README Demo 3)."
                    },
                    "removeScripts": {
                        "title": "Remove scripts",
                        "type": "boolean",
                        "description": "Strip JavaScript and tracking scripts",
                        "default": true
                    },
                    "removeStyles": {
                        "title": "Remove styles",
                        "type": "boolean",
                        "description": "Strip CSS and style tags",
                        "default": true
                    },
                    "includeMetadata": {
                        "title": "Include metadata",
                        "type": "boolean",
                        "description": "Return language, word_count, and processing_time_ms",
                        "default": true
                    },
                    "extractMentions": {
                        "title": "Extract @mentions",
                        "type": "boolean",
                        "description": "Pull @mentions from social HTML",
                        "default": false
                    },
                    "extractHashtags": {
                        "title": "Extract #hashtags",
                        "type": "boolean",
                        "description": "Pull hashtags from social HTML",
                        "default": false
                    }
                }
            },
            "runsResponseSchema": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "object",
                        "properties": {
                            "id": {
                                "type": "string"
                            },
                            "actId": {
                                "type": "string"
                            },
                            "userId": {
                                "type": "string"
                            },
                            "startedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "finishedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "status": {
                                "type": "string",
                                "example": "READY"
                            },
                            "meta": {
                                "type": "object",
                                "properties": {
                                    "origin": {
                                        "type": "string",
                                        "example": "API"
                                    },
                                    "userAgent": {
                                        "type": "string"
                                    }
                                }
                            },
                            "stats": {
                                "type": "object",
                                "properties": {
                                    "inputBodyLen": {
                                        "type": "integer",
                                        "example": 2000
                                    },
                                    "rebootCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "restartCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "resurrectCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "computeUnits": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "options": {
                                "type": "object",
                                "properties": {
                                    "build": {
                                        "type": "string",
                                        "example": "latest"
                                    },
                                    "timeoutSecs": {
                                        "type": "integer",
                                        "example": 300
                                    },
                                    "memoryMbytes": {
                                        "type": "integer",
                                        "example": 1024
                                    },
                                    "diskMbytes": {
                                        "type": "integer",
                                        "example": 2048
                                    }
                                }
                            },
                            "buildId": {
                                "type": "string"
                            },
                            "defaultKeyValueStoreId": {
                                "type": "string"
                            },
                            "defaultDatasetId": {
                                "type": "string"
                            },
                            "defaultRequestQueueId": {
                                "type": "string"
                            },
                            "buildNumber": {
                                "type": "string",
                                "example": "1.0.0"
                            },
                            "containerUrl": {
                                "type": "string"
                            },
                            "usage": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "integer",
                                        "example": 1
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "usageTotalUsd": {
                                "type": "number",
                                "example": 0.00005
                            },
                            "usageUsd": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "number",
                                        "example": 0.00005
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
```
