# Sitemap & Broken Link Checker - Fast XML Crawler & 404 Auditor (`abi4/sitemap-broken-link-checker`) Actor

High-speed sitemap and link crawler. Recursively parses XML/GZ sitemaps, verifies HTTP status codes (200, 301, 404, 500), maps redirect chains, and exports clean sitemaps.

- **URL**: https://apify.com/abi4/sitemap-broken-link-checker.md
- **Developed by:** [Abi](https://apify.com/abi4) (community)
- **Categories:**
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.70 / 1,000 verified urls

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

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

## Sitemap & Broken Link Checker - Fast XML Crawler & 404 Auditor

A resilient, ultra-fast sitemap crawler and link health auditor built on **Crawlee for Python**. Automatically discovers, decompresses, and crawls XML sitemaps, verifies HTTP response status codes (200, 301, 404, 500), maps redirect hops, and exports a cleaned `sitemap.xml` with dead links excluded.

***

### 🚀 Why Choose This Actor?

Many legacy sitemap tools frequently crash on gzip-compressed files (`.xml.gz`), fail on nested sitemap indexes, or lack the ability to check HTTP status codes.

**Sitemap & Broken Link Checker** solves this with an asynchronous, high-concurrency engine:

- **Universal Sitemap Support**: Handles standard XML, `.xml.gz` gzip archives, nested `<sitemapindex>` trees, and automated `robots.txt` sitemap discovery.
- **Deep HTTP Status Verification**: Tests URLs with asynchronous HTTP HEAD requests (falling back to GET), verifying 200 OK, 301/302 redirects, and 404/500 errors.
- **Redirect Chain Mapping**: Accurately traces multi-hop redirects (e.g., HTTP -> HTTPS -> Non-www) and flags circular loops.
- **Clean Sitemap Export**: Automatically writes a fresh, sanitized `sitemap.xml` to Key-Value Store with broken URLs removed—ready to submit to Google Search Console or Bing Webmaster Tools.
- **Ultra-Low Resource Footprint**: Runs in a lightweight 256 MB – 512 MB RAM footprint at 25–50 URLs per second, saving up to 90% in platform compute costs compared to heavy browser crawlers.

***

### ⚡ How to Use in 3 Simple Steps

1. **Enter Target Domain or Sitemap URL**: Paste your website root (e.g. `https://example.com`) or a direct XML URL (e.g. `https://example.com/sitemap.xml`) into **Start URLs**.
2. **Configure Scope**: Set `maxUrls` (e.g., `100` for a health check or `10000` for a large domain) and keep `autoDiscoverSitemap` and `checkStatus` checked.
3. **Run & Review**: Click **Start**. Review your overall site health percentage in the console, or open the **Key-Value Store** tab to download your `BROKEN_LINKS` list and `CLEAN_SITEMAP`.

***

### 📊 Key-Value Store Outputs

- **`OUTPUT`**: Machine-readable JSON summary containing total URLs, valid count, broken count, redirect count, and overall health score.
- **`BROKEN_LINKS`**: Filtered JSON inventory of all dead 404s and 500s, including response latency and the originating sitemap file.
- **`CLEAN_SITEMAP`**: Valid, standards-compliant XML sitemap containing only healthy, verified URLs, ready for direct search engine submission.

***

### 💡 Real-World Use Cases

- **SEO & Technical Site Migrations**: Audit sitemaps before and after domain migrations to catch unintended 404s and permanent redirect chains.
- **Google Search Console Cleanup**: Remove dead and redirected URLs from your sitemap to protect crawl budget and improve indexing velocity.
- **Continuous CI/CD Monitoring**: Run on an automated Apify schedule (e.g. weekly or monthly) to catch broken links before they harm organic rankings.

***

### ❓ FAQ & Support

#### Can this Actor discover sitemaps automatically?

Yes. If you provide a standard domain URL (e.g. `https://example.com`), the Actor will automatically query `robots.txt` for `Sitemap:` directives and check standard paths (`/sitemap.xml`, `/sitemap_index.xml`).

#### Does it support gzipped `.xml.gz` sitemaps?

Yes. It detects gzip compression automatically and decompresses the XML stream in memory without writing temporary files to disk.

#### Need custom features or have feedback?

Submit an inquiry via the **Issues** tab on Apify Console. We respond promptly and continually maintain this Actor.

# Actor input Schema

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

Enter your website domain (e.g. https://example.com) or direct sitemap XML URL (e.g. https://example.com/sitemap.xml).

## `autoDiscoverSitemap` (type: `boolean`):

If enabled, automatically checks robots.txt and standard paths (/sitemap.xml, /sitemap\_index.xml) to discover sitemaps.

## `checkStatus` (type: `boolean`):

Asynchronously test every URL to detect 404 Not Found, 500 Server Errors, and redirect chains.

## `maxUrls` (type: `integer`):

Maximum number of URLs to extract and verify.

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

Maximum number of parallel HTTP requests.

## `exportCleanSitemap` (type: `boolean`):

Outputs a cleaned sitemap.xml to Key-Value Store with all 404 broken links excluded.

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

Use Apify Proxy or custom proxies for bot-protected websites.

## `alertSlackWebhookUrl` (type: `string`):

Optional Slack webhook URL to notify when broken links are detected.

## `alertEmailAddresses` (type: `array`):

List of email addresses to notify if broken URLs exceed the alert threshold.

## `alertMinBrokenCount` (type: `integer`):

Trigger Slack/Email alerts only if the number of broken URLs is greater than or equal to this threshold.

## `enableHistoricalDiff` (type: `boolean`):

Compare current sitemap crawl against the previous run to detect newly added, removed, newly broken, and recovered URLs.

## `baselineDatasetId` (type: `string`):

Optional specific Apify Dataset ID to use as the historical baseline. If blank, automatically compares against the most recent task run.

## `generateVisualTree` (type: `boolean`):

Synthesize interactive sitemap hierarchy tree maps (SITEMAP\_TREE.html and SITEMAP\_TREE.mermaid) in Key-Value Store.

## Actor input object example

```json
{
  "startUrls": [
    {
      "url": "https://example.com"
    }
  ],
  "autoDiscoverSitemap": true,
  "checkStatus": true,
  "maxUrls": 100,
  "maxConcurrency": 10,
  "exportCleanSitemap": true,
  "proxyConfiguration": {
    "useApifyProxy": false
  },
  "alertSlackWebhookUrl": "",
  "alertEmailAddresses": [],
  "alertMinBrokenCount": 1,
  "enableHistoricalDiff": false,
  "baselineDatasetId": "",
  "generateVisualTree": true
}
```

# Actor output Schema

## `dataset` (type: `string`):

No description

## `brokenLinks` (type: `string`):

No description

## `cleanSitemap` (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 = {
    "startUrls": [
        {
            "url": "https://example.com"
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("abi4/sitemap-broken-link-checker").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" }] }

# Run the Actor and wait for it to finish
run = client.actor("abi4/sitemap-broken-link-checker").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"
    }
  ]
}' |
apify call abi4/sitemap-broken-link-checker --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,abi4/sitemap-broken-link-checker"
        }
    }
}

```

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/NsM5bD8hI99kgEE4i/builds/nrApPoiPKA1sn8pGe/openapi.json
