惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Forbes - Security
Forbes - Security
The Register - Security
The Register - Security
G
Google Developers Blog
罗磊的独立博客
WordPress大学
WordPress大学
L
LangChain Blog
博客园 - 三生石上(FineUI控件)
Recorded Future
Recorded Future
Microsoft Azure Blog
Microsoft Azure Blog
Google DeepMind News
Google DeepMind News
大猫的无限游戏
大猫的无限游戏
MongoDB | Blog
MongoDB | Blog
小众软件
小众软件
Recent Announcements
Recent Announcements
T
Tailwind CSS Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
云风的 BLOG
云风的 BLOG
Apple Machine Learning Research
Apple Machine Learning Research
酷 壳 – CoolShell
酷 壳 – CoolShell
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
F
Full Disclosure
The Cloudflare Blog
B
Blog RSS Feed
S
Schneier on Security
T
Tenable Blog
人人都是产品经理
人人都是产品经理
Engineering at Meta
Engineering at Meta
T
Tor Project blog
N
Netflix TechBlog - Medium
T
Threatpost
NISL@THU
NISL@THU
Stack Overflow Blog
Stack Overflow Blog
N
News | PayPal Newsroom
N
News and Events Feed by Topic
aimingoo的专栏
aimingoo的专栏
博客园 - 叶小钗
P
Privacy & Cybersecurity Law Blog
C
CERT Recently Published Vulnerability Notes
Last Week in AI
Last Week in AI
M
MIT News - Artificial intelligence
C
CXSECURITY Database RSS Feed - CXSecurity.com
P
Privacy International News Feed
博客园 - 【当耐特】
Help Net Security
Help Net Security
The Hacker News
The Hacker News
Hugging Face - Blog
Hugging Face - Blog
TaoSecurity Blog
TaoSecurity Blog
S
Secure Thoughts
C
Cisco Blogs
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How to Build Token-Efficient Web Scraping Pipelines for AI Agents Using n8n
AlterLab · 2026-05-27 · via DEV Community

TL;DR

Building token-efficient scraping pipelines for AI agents requires stripping heavy HTML DOM structures into clean, semantic Markdown before inference. By combining n8n for visual pipeline orchestration with AlterLab for headless extraction, engineering teams can reduce token consumption by up to 90% while providing LLMs with high-fidelity, highly contextual web data.

The Context Window Problem: HTML vs. LLMs

AI agents rely on context windows to understand the data they are processing. When building Autonomous Agents, Retrieval-Augmented Generation (RAG) systems, or LLM-driven research tools, developers often default to passing raw HTML directly into the model.

This is an architectural anti-pattern.

A modern e-commerce product page or a long-form documentation article often exceeds 2MB of raw HTML. When tokenized by standard models (like tiktoken for OpenAI), a single page can consume 30,000 to 100,000 tokens.

Passing raw HTML creates three immediate problems:

  1. Cost Accumulation: Processing 50,000 tokens per web page across thousands of URLs leads to exorbitant API costs.
  2. Context Dilution: LLMs suffer from the "lost in the middle" phenomenon. Massive amounts of irrelevant HTML attributes, inline CSS, and SVG paths dilute the core textual content.
  3. Latency: Larger input payloads require longer processing times from the LLM provider, slowing down the autonomous agent's decision loop.

To build scalable AI agents, the data pipeline must act as a precise filter, transforming structural web chaos into token-efficient formats. Markdown is the optimal format: it retains structural hierarchy (headers, lists, tables) while dropping DOM noise.

Core Architecture: Integrating n8n with Scraping APIs

n8n is a workflow automation tool that excels at routing and transforming data. To build a robust pipeline, we separate concerns: an external API handles the infrastructure of fetching the page, and n8n handles the transformation and AI orchestration.

The architecture follows a strict sequence:

  1. Trigger: The agent identifies a URL it needs to read.
  2. Extraction: An HTTP Request calls an extraction API to fetch the fully rendered HTML.
  3. Transformation (The Token Saver): The HTML is stripped of <script>, <style>, and <nav> tags, then parsed into pure Markdown.
  4. Ingestion: The Markdown is fed into the AI Agent node for processing.

Building the Pipeline: Step-by-Step

Let's construct the pipeline in n8n. We will start by defining the extraction mechanism, configuring the n8n nodes, and implementing the Markdown conversion logic.

Step 1: The Data Extraction Engine

Before configuring n8n, you must establish how you will fetch the data. Modern web pages rely heavily on client-side rendering (React, Vue, Angular). A simple GET request will often return an empty <div>, depriving your AI agent of the actual content.

You need a solution that executes JavaScript and waits for network idle states. While you can maintain your own Puppeteer or Playwright cluster, using a dedicated API simplifies the pipeline. For this tutorial, we will use our own infrastructure, handling complex anti-bot handling and browser rendering behind a single API call.

Here is how the request is structured. We require a POST request containing the target URL.

```bash title="Terminal" {2-4}
curl -X POST https://api.alterlab.io/v1/scrape \
-H "X-API-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com/public-article", "render_js": true}'




If you are testing your logic outside of n8n first, you can utilize the [Python SDK](https://alterlab.io/web-scraping-api-python) to prototype the extraction.



```python title="extractor.py" {4-7}

client = alterlab.Client("YOUR_API_KEY")
response = client.scrape(
    url="https://example.com/public-article",
    render_js=True
)

print(f"Retrieved {len(response.text)} bytes of HTML")

Enter fullscreen mode Exit fullscreen mode

To set this up quickly, ensure you have your API keys ready by following the quickstart guide.

Step 2: Configuring the n8n HTTP Request Node

In your n8n canvas, create an HTTP Request node. This node replaces the curl command above and acts as the bridge between your workflow and the extraction engine.

Configure the node with the following parameters:

  • Method: POST
  • URL: https://api.alterlab.io/v1/scrape
  • Authentication: Set up a Header Auth credential or pass it directly in the headers.
  • Send Headers:
    • Name: X-API-Key, Value: your_api_key
    • Name: Content-Type, Value: application/json
  • Send Body: Enable this option.
  • Body Parameters:
    • Name: url, Value: ={{ $json.targetUrl }} (Assuming the URL is passed from the previous node).
    • Name: render_js, Value: true (Boolean).

In the Node settings, ensure you set Retry On Fail to true with a wait time of 2-3 seconds. Web scraping is inherently volatile due to network timeouts; implementing retries at the HTTP node level guarantees a more resilient AI agent.

Step 3: DOM Stripping and Markdown Conversion

This is the most critical step for token efficiency. The HTTP Request node will output a massive string of raw HTML. We must condense this before it reaches the LLM.

Add a Code node in n8n immediately following the HTTP Request node. We will use standard JavaScript and a Markdown conversion library (like Turndown, which is often accessible or easily implemented via custom scripts in n8n).

If you do not have external libraries enabled in your n8n environment, you can use a combination of the HTML Extract node and Regex within a Code node to strip the heaviest elements.

First, use an HTML Extract node:

  • Extraction Values:
    • Key: main_content
    • CSS Selector: main, article, #content, .content-body (Targeting semantic tags is safer than targeting the entire <body>).
    • Return Value: HTML

Next, pipe that into a Code node to clean the extracted HTML and parse it into pseudo-markdown or clean text.

```javascript title="n8n_code_node.js" {5-9, 13-14}
// Access the HTML extracted from the previous node
let rawHtml = $input.first().json.main_content;

// 1. Strip massive token-wasters via Regex
rawHtml = rawHtml.replace(/)&lt;[^&lt;]<em>)</em>&lt;\/script&gt;/gi, &#39;&#39;);<br> rawHtml = rawHtml.replace(/<style\b[^<]*(?:(?!<\/style>)&lt;[^&lt;]<em>)</em>&lt;\/style&gt;/gi, &#39;&#39;);<br> rawHtml = rawHtml.replace(/<svg\b[^<]*(?:(?!<\/svg>)&lt;[^&lt;]<em>)</em>&lt;\/svg&gt;/gi, &#39;[IMAGE]&#39;);<br> rawHtml = rawHtml.replace(/data:image\/[^;]+;base64,[^&quot;]+/gi, &#39;&#39;);</p> <p>// 2. Convert remaining structural elements to basic Markdown<br> let markdown = rawHtml<br> .replace(/<h1[^>]<em>&gt;(.</em>?)&lt;\/h1&gt;/gi, &#39;# $1\n\n&#39;)<br> .replace(/<h2[^>]<em>&gt;(.</em>?)&lt;\/h2&gt;/gi, &#39;## $1\n\n&#39;)<br> .replace(/<h3[^>]<em>&gt;(.</em>?)&lt;\/h3&gt;/gi, &#39;### $1\n\n&#39;)<br> .replace(/<a[^>]<em>href=&quot;([^&quot;]+)&quot;[^&gt;]</em>&gt;(.*?)&lt;\/a&gt;/gi, &#39;<a href="https://dev.to$1">$2</a>&#39;)<br> .replace(/&lt;[^&gt;]+&gt;/g, &#39;&#39;); // Strip remaining tags</p> <p>// 3. Clean up excessive whitespace<br> markdown = markdown.replace(/\n\s*\n/g, &#39;\n\n&#39;).trim();</p> <p>return {<br> json: {<br> optimized_content: markdown,<br> original_length: rawHtml.length,<br> optimized_length: markdown.length<br> }<br> };</p> <div class="highlight"><pre class="highlight plaintext"><code> By executing this Code node, you effectively reduce a 150KB HTML payload into a 15KB Markdown payload. ### Step 4: Connecting the AI Agent Node Now that the data is sanitized and token-optimized, it is ready for the LLM. Add an **Advanced AI** node (or a standard OpenAI/Anthropic node depending on your n8n version). Configure the AI node's prompt to utilize the injected Markdown: * **System Message:** "You are a data extraction assistant. You will be provided with the Markdown representation of a web page. Extract the core arguments and data points requested by the user." * **User Message:** ```text Analyze the following web page content and extract the pricing tiers. PAGE CONTENT: ={{ $json.optimized_content }} ``` Because the input is structured Markdown, the LLM will parse headers and lists with perfect semantic understanding, generating faster and more accurate responses compared to parsing raw HTML trees. ## Advanced Optimization: Targeted Selectors vs. Full Page Extraction If your AI agent is operating on known, structured domains (e.g., pulling metrics from public financial databases or specific software documentation), you can bypass the Markdown conversion step entirely by utilizing targeted CSS selectors directly in your extraction API request. Instead of pulling the full DOM and processing it in n8n, instruct the scraping engine to only return specific nodes. This pushes the filtering logic to the edge, saving bandwidth and execution time in n8n. Modify the HTTP Request node body to pass an array of selectors: ```json title="HTTP Node Body" {4-7} { "url": "https://example.com/public-directory", "render_js": true, "extract_rules": { "title": "h1.header-title", "metrics": ".stats-grid .metric-value", "description": "article p:first-of-type" } } </code></pre></div> <p></p> <p>When the extraction API supports edge-parsing, the HTTP node will receive a clean JSON object containing only the requested text. This represents the absolute peak of token efficiency. The payload is no longer HTML or Markdown—it is a strict key-value pair map.</p> <p>When passing structured JSON to an LLM, the token count is minimized to only the precise data points required for the agent&#39;s task.</p> <h2> <a name="measuring-the-token-savings" href="#measuring-the-token-savings" class="anchor"> </a> Measuring the Token Savings </h2> <p>It is critical to measure the impact of this pipeline. In a standard workflow running 1,000 pages a day:</p> <ul> <li> <strong>Raw HTML Method:</strong> Average 40,000 tokens per page. Total: 40,000,000 input tokens. At standard GPT-4o pricing ($5.00 / 1M input tokens), this costs $200 per day.</li> <li> <strong>Markdown Pipeline Method:</strong> Average 4,000 tokens per page. Total: 4,000,000 input tokens. Cost: $20 per day.</li> </ul> <p>By implementing this n8n pipeline, you achieve a 90% reduction in LLM inference costs while simultaneously improving the precision of the model&#39;s outputs.</p> <h2> <a name="takeaways" href="#takeaways" class="anchor"> </a> Takeaways </h2> <p>Feeding LLMs directly with raw web data is an inefficient, expensive practice that degrades agent performance. By leveraging n8n&#39;s visual workflow capabilities alongside a robust extraction API, developers can enforce strict data hygiene. </p> <ul> <li> <strong>Render first, process second:</strong> Always ensure JavaScript is executed before pulling the DOM.</li> <li> <strong>Strip the noise:</strong> Use n8n Code or HTML Extract nodes to remove <code>&lt;script&gt;</code>, <code>&lt;style&gt;</code>, and SVG data.</li> <li> <strong>Convert to Markdown:</strong> Translate structural HTML into LLM-friendly formatting.</li> <li> <strong>Target when possible:</strong> If the schema is known, use CSS selectors at the extraction edge to return pure JSON instead of full documents.</li> </ul> <p>Implement these token-efficient pipelines to scale your autonomous agents without scaling your API billing.</p>