Skip to content

About

Browserless login-free Substack scraper harvesting newsletter publications, full article bodyText/bodyHtml for AI RAG pipelines, nested comment trees, Restacks, top search notes, and author contact leads via _preloads and Archive API.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

21 Commits

Folders and files

Repository files navigation

📰 Substack Ultimate Scraper

Zero-Browser, Login-Free Newsletter Harvester: _preloads, Archive API, Full-Text RAG Body, Nested Comments & Top Search

API & RSS Pipeline • 5 Modes & Inputs • Output Payloads • Execution Guides

Actor Name Pure HTTP AI Ready Text Version 1.0.0

Node 20 got-scraping Crawlee Apify SDK License

Tech Stack


⚡ API & RSS Ingestion Pipeline

Unlike heavy browser crawlers, src/main.js executes 100% over high-speed Chrome-fingerprinted HTTP (got-scraping >= Chrome 124) — zero Chromium tabs spawned at runtime (note: playwright is declared in package.json and the base Docker image, while all runtime requests use httpRequest() via got-scraping).

flowchart LR
    Input["targetUrls (subdomain, custom domain, @handle, /p/slug) + searchKeywords"] --> Norm["normalizeSubstackUrl() + detectSubstackTargetType()"]

    Norm -- "PUBLICATIONS / POSTS / COMMENTS" --> Ctx["fetchPublicationContext()\n1. Homepage preloads-json / window._preloads\n2. Fallback RSS /feed XML (custom domains)"]

    Ctx -- "Single Post (/p/slug)" --> SingleApi["GET /api/v1/posts/{slug}"]
    Ctx -- "Publication Archive" --> ArchiveApi["Cursor Loop: GET /api/v1/archive?sort=new&limit=25"]
    ArchiveApi -- "Missing body_html & extractFullText" --> FullFetch["Hydrate via /api/v1/posts/{slug}"]
    ArchiveApi -- "API blocked / empty" --> RssFallback["parseRssFeed() XML Backup"]

    SingleApi & FullFetch --> Comments{"maxComments > 0?"}
    Comments -- "Yes" --> CommentsApi["GET /api/v1/post/{id}/comments?all_comments=true&sort=top\nparseCommentsList() flattens nested c.children"]

    Norm -- "SEARCH / searchKeywords[]" --> TopSearch["GET substack.com/api/v1/top/search?query=...\nHandles post articles + comment Notes + legacy items"]

    CommentsApi & RssFallback & TopSearch --> Store["Dataset + OUTPUT KV Summary (COMPLETED / PARTIAL_SUCCESS / FAILED)"]
Loading

Verified Engineering Highlights

  • Custom Domain Canonical Resolution: Follows homepage HTTP redirects (homeRes.finalUrl) to resolve custom Substack newsletter domains (pragmaticengineer.com) before calling /api/v1/... or /feed.
  • Clean RAG Plain-Text Conversion (htmlToPlainText): Strips <script> and <style>, converts structural <br>, </p>, </h1..6>, and <li> tags cleanly, decodes HTML/numeric entities, estimates readingTimeMinutes at 220 WPM, and outputs both bodyText and raw bodyHtml. (Note: does not emit Markdown syntax — produces clean plain text + HTML.)
  • Contact Lead Enrichment: Scans bios and first 5,000 chars of post text via extractEmails(), extractPhones(), and extractSocialLinks() (ignoring substack.com system domains).
  • Cloudflare Shield Detection: Detects just a moment..., cf-browser-verification, cf-turnstile, and HTTP 429/5xx, retrying with linear backoff (2000 * (attempt + 1) ms) and dropping broken proxies on 597/407/UPSTREAM407.

🎛️ 5 Extraction Modes & Input Schema

Configured in .actor/input_schema.json:

Parameter Type Default Description & Runtime Behavior
mode string "AUTO_DETECT" AUTO_DETECT, PUBLICATIONS, POSTS, COMMENTS, or SEARCH.
targetUrls string[] Prefill: ["https://thealgorithmicbridge.substack.com"] Accepts full URLs, bare subdomains (astralcodexten), custom domains, or @handles. Defaults to thealgorithmicbridge.substack.com if both URLs and keywords are empty.
searchKeywords string[] Prefill: ["artificial intelligence agents"] Queries https://substack.com/api/v1/top/search with cursor pagination.
maxPosts integer 30 0 – 5000 posts per publication or search query (0 unlocks unlimited Infinity full-archive crawl).
maxComments integer 20 0 – 1000 nested reader comments flattened per post.
extractFullText boolean true Hydrates full bodyText & bodyHtml via /api/v1/posts/{slug} when archive omits body_html.
proxyConfiguration object { "useApifyProxy": true } Apify Proxy config; RESIDENTIAL recommended for heavy archive crawls.

📦 LLM-Ready Record Anatomy

📄 4 Record Types Emitted (POST, PUBLICATION, COMMENT, SEARCH_RESULT) + OUTPUT

1. Article Record (type: "POST"):

{
  "type": "POST",
  "id": "145678901",
  "url": "https://thealgorithmicbridge.substack.com/p/why-ai-agents-matter",
  "title": "Why AI Agents Are the Next Computing Platform",
  "subtitle": "An in-depth analysis of autonomous agentic architectures.",
  "slug": "why-ai-agents-matter",
  "bodyText": "Over the past six months, the focus of generative AI has decisively shifted...",
  "bodyHtml": "<p>Over the past six months...</p>",
  "publicationName": "The Algorithmic Bridge",
  "publicationUrl": "https://thealgorithmicbridge.substack.com",
  "primaryAuthor": "Alberto Romero",
  "authors": [
    {
      "id": 12345,
      "name": "Alberto Romero",
      "handle": "albertoromero",
      "twitter": "https://x.com/Alber_Romero"
    }
  ],
  "likesCount": 420,
  "commentsCount": 35,
  "restacksCount": 18,
  "isPaid": false,
  "audience": "everyone",
  "wordCount": 1850,
  "readingTimeMinutes": 9,
  "source": "substack_archive_api",
  "publishedAt": "2026-10-08T14:00:00.000Z",
  "scrapedAt": "2026-11-18T12:45:00.000Z"
}

2. Publication (PUBLICATION), Comment (COMMENT), & Search (SEARCH_RESULT):

  • PUBLICATION: publicationName, publicationSubdomain, publicationUrl, description, publicationLogoUrl, subscriberHint, email, socialLinks.
  • COMMENT: postId, url, commentText, commentAuthor, commentHandle, commentLikes, publishedAt, source: "substack_comments_api".
  • SEARCH_RESULT: Captures both full essays (item.post) and short Substack Notes (item.comment mapped to /@{handle}/note/c-{id}) with searchQuery & source: "substack_search_api".

3. Key-Value Store OUTPUT:

{
  "status": "COMPLETED",
  "timestamp": "2026-11-18T12:46:00.000Z",
  "metrics": {
    "publications": 1,
    "posts": 30,
    "comments": 140,
    "searchResults": 25,
    "failed": 0
  },
  "totalRecordsExtracted": 196,
  "message": "Substack Ultimate Scraper completed successfully."
}

🚀 Deployment: Apify, Local Node & Docker

1. Apify Cloud & apify-client

{
  "mode": "PUBLICATIONS",
  "targetUrls": [
    "https://thealgorithmicbridge.substack.com",
    "https://pragmaticengineer.com"
  ],
  "maxPosts": 50,
  "maxComments": 20,
  "extractFullText": true,
  "proxyConfiguration": { "useApifyProxy": true }
}
import { ApifyClient } from 'apify-client';

const client = new ApifyClient({ token: process.env.APIFY_TOKEN });
const run = await client.actor('khalid-naami/substack-ultimate-scraper').call({
    mode: 'SEARCH',
    searchKeywords: ['artificial intelligence agents'],
    maxPosts: 25,
    extractFullText: true,
});
const { items } = await client.dataset(run.defaultDatasetId).listItems();
console.log(items);

2. Isolated Local Environment (Node.js 20)

No Playwright browser launch happens at runtime in src/main.js, making local setup lightweight:

git clone https://github.com/khalid-naami/actor-substack-scraper.git
cd actor-substack-scraper
npm install

Windows PowerShell:

New-Item -ItemType Directory -Force -Path ".\storage\key_value_stores\default" | Out-Null

@'
{
  "mode": "PUBLICATIONS",
  "targetUrls": ["https://thealgorithmicbridge.substack.com"],
  "maxPosts": 10,
  "maxComments": 5,
  "extractFullText": true
}
'@ | Set-Content -Encoding UTF8 ".\storage\key_value_stores\default\INPUT.json"

$env:APIFY_LOCAL_STORAGE_DIR = "$PWD\storage"
$env:CRAWLEE_STORAGE_DIR = "$PWD\storage"
npm start

Linux / macOS (Bash):

mkdir -p ./storage/key_value_stores/default
cat <<'EOF' > ./storage/key_value_stores/default/INPUT.json
{
  "mode": "PUBLICATIONS",
  "targetUrls": ["https://thealgorithmicbridge.substack.com"],
  "maxPosts": 10,
  "maxComments": 5,
  "extractFullText": true
}
EOF
APIFY_LOCAL_STORAGE_DIR="$(pwd)/storage" CRAWLEE_STORAGE_DIR="$(pwd)/storage" npm start

(Note: in package.json, npm test runs node src/main.js directly rather than syntax-only --check.)

3. Docker Execution (FROM apify/actor-node-playwright:20)

docker build -t actor-substack-scraper .
# Windows PowerShell
docker run --rm `
  -v "${PWD}/storage:/tmp/apify-storage" `
  -e APIFY_LOCAL_STORAGE_DIR=/tmp/apify-storage `
  -e CRAWLEE_STORAGE_DIR=/tmp/apify-storage `
  -e APIFY_DISABLE_BROWSER_SANDBOX=1 `
  actor-substack-scraper
# Linux / macOS
docker run --rm \
  -v "$(pwd)/storage:/tmp/apify-storage" \
  -e APIFY_LOCAL_STORAGE_DIR=/tmp/apify-storage \
  -e CRAWLEE_STORAGE_DIR=/tmp/apify-storage \
  -e APIFY_DISABLE_BROWSER_SANDBOX=1 \
  actor-substack-scraper

⚖️ License & Repository Notes

  • LICENSE contains the MIT License (Copyright (c) 2026 khalidnaami7), while package.json declares "license": "Apache-2.0".
  • package.json lists playwright: ^1.49.1 and Dockerfile extends apify/actor-node-playwright:20, though all scraping routes execute through got-scraping HTTP requests.

About

Browserless login-free Substack scraper harvesting newsletter publications, full article bodyText/bodyHtml for AI RAG pipelines, nested comment trees, Restacks, top search notes, and author contact leads via _preloads and Archive API.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages