# Scraped Text Sanitizer (`nibble/scraped-text-sanitizer`) Actor

Fix mojibake, decode HTML entities, strip HTML tags, NFKC-normalize, and collapse whitespace in text records you supply.

- **URL**: https://apify.com/nibble/scraped-text-sanitizer.md
- **Developed by:** [Simon Fletcher](https://apify.com/nibble) (community)
- **Categories:** Developer tools
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $2.00 / 1,000 record cleaneds

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

Scraped Text Sanitizer **repairs dirty, garbled text** in records you already have — no scraping, no login, no API keys. Paste an array of records (or a single string) and it fixes **mojibake**, decodes **HTML entities**, strips **leftover HTML tags**, applies **Unicode NFKC normalization**, optionally **removes emoji**, and **collapses whitespace** — every step individually toggleable. You get back clean text plus a per-record summary of exactly what changed.

It runs on the Apify platform, so you get API access, scheduling, integrations (Make, Zapier, n8n), and pay-per-record billing with no infrastructure to manage.

### What does Scraped Text Sanitizer do?

Text harvested from the web, PDFs, CSV exports, or old databases is frequently broken: `CafÃ©` instead of `Café`, `Tom &amp; Jerry` instead of `Tom & Jerry`, stray `<p>`/`<span>` tags, fullwidth and ligature characters, and messy whitespace. This Actor cleans all of that in one pass. It **only transforms data you supply** — it never fetches, crawls, or logs into anything.

Under the hood it uses the battle-tested [ftfy](https://ftfy.readthedocs.io/) library for mojibake repair, Python's standard `html` and `unicodedata` for entity decoding and NFKC normalization, and deterministic rules for tag stripping and whitespace collapsing.

### Why use Scraped Text Sanitizer?

- **Fix mojibake at scale** — repair `Ã©`, `â€™`, and other encoding damage without writing a script.
- **Clean up scraper output** — decode entities and strip HTML tags that leak into extracted text.
- **Normalize for search & dedup** — NFKC folds fullwidth forms and ligatures so records match.
- **Full transparency** — every record reports which operations changed it, so you can trust the result.
- **No code, no servers** — run on demand, on a schedule, or from your own app via the Apify API.

### How to use Scraped Text Sanitizer

1. Open the Actor and go to the **Input** tab.
2. Paste your records into the **Records to clean** field (an array of strings, or objects with a `text` field). Optionally add a single **text** string.
3. Toggle the cleaning operations you want (all on by default except *Strip emoji*).
4. Click **Start**. When it finishes, open the **Output** tab or download the dataset as JSON, CSV, Excel, or HTML.

### Input

| Field | Type | Description |
|-------|------|-------------|
| `records` | array | Records to clean. Each item is a string, or an object containing the text field named by `textField`. Add an `id` to join results back to your source. |
| `text` | string | Optional single string to clean, processed in addition to `records`. |
| `textField` | string | For object records, the property holding the text (default `text`). |
| `fixMojibake` | boolean | Repair encoding damage / mojibake (default `true`). |
| `decodeHtmlEntities` | boolean | `&amp;` → `&`, `&lt;` → `<` (default `true`). |
| `stripHtmlTags` | boolean | Remove leftover HTML tags (default `true`). |
| `normalizeUnicode` | boolean | Unicode NFKC normalization (default `true`). |
| `stripEmoji` | boolean | Remove emoji and pictographs (default `false`). |
| `collapseWhitespace` | boolean | Collapse whitespace runs to single spaces and trim (default `true`). |

#### Input example

```json
{
  "records": [
    { "id": "a", "text": "Caf&eacute; &amp; CrÃªpes <b>Paris</b>   " },
    { "id": "b", "text": "Rock &amp; RÃ¶ll ﬁnale" }
  ],
  "stripEmoji": false
}
```

### Output

Each input record produces one dataset item with the cleaned text and a change summary. You can download the dataset in various formats such as JSON, HTML, CSV, or Excel.

```json
{
  "id": "a",
  "recordIndex": 0,
  "cleanedText": "Café & Crêpes Paris",
  "originalText": "Caf&eacute; &amp; CrÃªpes <b>Paris</b>   ",
  "changed": true,
  "changes": {
    "fixedMojibake": true,
    "decodedHtmlEntities": true,
    "strippedHtmlTags": true,
    "normalizedUnicode": false,
    "collapsedWhitespace": true
  },
  "originalLength": 41,
  "cleanedLength": 19,
  "billed": true
}
```

#### Output fields

| Field | Type | Description |
|-------|------|-------------|
| `id` | string/number | Pass-through identifier from the input record, if supplied. |
| `recordIndex` | integer | Zero-based position of the record in the processed input. |
| `cleanedText` | string | The sanitized text after all enabled operations. |
| `originalText` | string | The exact input text before cleaning. |
| `changed` | boolean | `true` if the cleaned text differs from the original. |
| `changes` | object | Per-operation flags — `true` if that enabled operation modified the text. Only enabled operations appear. |
| `originalLength` | integer | Character count of the original text. |
| `cleanedLength` | integer | Character count of the cleaned text. |
| `billed` | boolean | `true` if the record was charged as a paid result (non-empty output under pay-per-event). |

### Pricing

This Actor uses **pay-per-result** billing: you are charged once per **non-empty cleaned record**. Empty or whitespace-only inputs are returned for transparency but are **never charged**. Compute is negligible (tens of thousands of records per second), so cost is dominated by the per-record price set in the Console. See `PRICING.md` for the unit-economics rationale.

### Tips

- Leave *Strip emoji* off unless you specifically need emoji removed — they are often meaningful content.
- Disable operations you don't need (e.g. keep HTML tags) via the toggles; the change summary reflects only the operations you enabled.
- Use the `id` field on records to join cleaned output back to your source rows.

### FAQ and support

- **Does it scrape or fetch anything?** No. It only transforms data you pass in as input. There is no network access, authentication, or PII harvesting.
- **What fixes mojibake?** The [ftfy](https://ftfy.readthedocs.io/) library's encoding repair, applied before entity decoding and normalization.
- **Something looks wrong?** Open the Issues tab with an example input and the expected output.

# Actor input Schema

## `records` (type: `array`):

Array of records to clean. Each item can be a plain string, or an object containing the text field named by 'Text field name' (default 'text'). Include an 'id' on objects to join results back to your source.

## `text` (type: `string`):

Convenience input for cleaning one string. Processed in addition to any 'records'.

## `textField` (type: `string`):

For object records, the property holding the text to clean.

## `fixMojibake` (type: `boolean`):

Repair encoding damage / mojibake (e.g. 'CafÃ©' -> 'Café') using ftfy.

## `decodeHtmlEntities` (type: `boolean`):

Turn HTML entities into characters (e.g. '&' -> '&', '<' -> '<').

## `stripHtmlTags` (type: `boolean`):

Remove leftover HTML tags such as <p>, <b>, <span>.

## `normalizeUnicode` (type: `boolean`):

Apply Unicode NFKC normalization (fullwidth forms, ligatures, compatibility characters).

## `stripEmoji` (type: `boolean`):

Remove emoji and pictographs. Off by default because emoji are often meaningful.

## `collapseWhitespace` (type: `boolean`):

Collapse runs of whitespace (spaces, tabs, newlines) to a single space and trim the ends.

## Actor input object example

```json
{
  "records": [
    {
      "id": 1,
      "text": "Caf&eacute; &amp; CrÃªpes <b>Paris</b>   "
    },
    {
      "id": 2,
      "text": "Rock &amp; RÃ¶ll  \n\n tour ﬁnale"
    }
  ],
  "textField": "text",
  "fixMojibake": true,
  "decodeHtmlEntities": true,
  "stripHtmlTags": true,
  "normalizeUnicode": true,
  "stripEmoji": false,
  "collapseWhitespace": 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 = {
    "records": [
        {
            "id": 1,
            "text": "Caf&eacute; &amp; CrÃªpes <b>Paris</b>   "
        },
        {
            "id": 2,
            "text": "Rock &amp; RÃ¶ll  \n\n tour ﬁnale"
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("nibble/scraped-text-sanitizer").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 = { "records": [
        {
            "id": 1,
            "text": "Caf&eacute; &amp; CrÃªpes <b>Paris</b>   ",
        },
        {
            "id": 2,
            "text": """Rock &amp; RÃ¶ll  

 tour ﬁnale""",
        },
    ] }

# Run the Actor and wait for it to finish
run = client.actor("nibble/scraped-text-sanitizer").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 '{
  "records": [
    {
      "id": 1,
      "text": "Caf&eacute; &amp; CrÃªpes <b>Paris</b>   "
    },
    {
      "id": 2,
      "text": "Rock &amp; RÃ¶ll  \\n\\n tour ﬁnale"
    }
  ]
}' |
apify call nibble/scraped-text-sanitizer --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=nibble/scraped-text-sanitizer",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/acts/ab6aFYvQUcPuZl4Zx/builds/mV9xiWroRzQTUtOuo/openapi.json
