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

推荐订阅源

Google DeepMind News
Google DeepMind News
I
Intezer
T
Tailwind CSS Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
IT之家
IT之家
Jina AI
Jina AI
V
Visual Studio Blog
E
Exploit-DB.com RSS Feed
爱范儿
爱范儿
The Cloudflare Blog
H
Help Net Security
P
Proofpoint News Feed
S
Security Affairs
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Blog — PlanetScale
Blog — PlanetScale
V
V2EX
N
News and Events Feed by Topic
Microsoft Azure Blog
Microsoft Azure Blog
Stack Overflow Blog
Stack Overflow Blog
博客园_首页
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
C
Cybersecurity and Infrastructure Security Agency CISA
T
Threat Research - Cisco Blogs
V
V2EX - 技术
Hugging Face - Blog
Hugging Face - Blog
A
Arctic Wolf
宝玉的分享
宝玉的分享
The GitHub Blog
The GitHub Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
量子位
酷 壳 – CoolShell
酷 壳 – CoolShell
Hacker News: Ask HN
Hacker News: Ask HN
Y
Y Combinator Blog
小众软件
小众软件
M
MIT News - Artificial intelligence
C
CERT Recently Published Vulnerability Notes
P
Proofpoint News Feed
N
Netflix TechBlog - Medium
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
G
GRAHAM CLULEY
AWS News Blog
AWS News Blog
MyScale Blog
MyScale Blog
B
Blog RSS Feed
博客园 - 聂微东
D
Darknet – Hacking Tools, Hacker News & Cyber Security
月光博客
月光博客
D
Docker
www.infosecurity-magazine.com
www.infosecurity-magazine.com
F
Full Disclosure

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
Replacing Fragile CSS Selectors with LLM-Powered Zero-Shot JSON Extraction
AlterLab · 2026-06-15 · via DEV Community

TL;DR

Zero-shot JSON extraction replaces brittle CSS selectors with Large Language Models that map unstructured web content to predefined schemas semantically. By processing cleaned HTML or Markdown through an LLM context window, scraping pipelines become resilient to UI changes, A/B tests, and dynamic class names. This approach shifts data engineering effort from constant selector maintenance to high-level schema definition, enabling truly agentic data collection.

The Selector Maintenance Trap

Web scraping pipelines eventually hit the same bottleneck: selector maintenance. Traditional data extraction relies on identifying structural patterns in the Document Object Model (DOM). You write rules targeting specific HTML nodes using tools like XPath, BeautifulSoup, or Cheerio.

A standard selector might look like div.product-details > span:nth-child(3) > b.price-tag.

This structural dependency is a massive liability. Modern front-end development practices have rendered static selectors obsolete. Frameworks like React and Vue dynamically inject DOM nodes. Styling solutions like Tailwind CSS or CSS-in-JS libraries generate randomized, utility-based class names (.css-1a2b3c, .tw-mt-4).

When a front-end team deploys a minor UI update or runs an A/B test, the structural path changes. The scraping pipeline breaks. The extraction script returns null values. Data engineering teams are forced into a reactive cycle, spending engineering cycles updating scripts for specific target sites instead of building core infrastructure. The maintenance cost scales linearly with the number of domains you track.

Enter Zero-Shot Semantic Extraction

Zero-shot extraction removes the structural dependency entirely. Instead of telling the code where to look in the DOM, you tell an LLM what data you want.

This represents a shift from structural mapping to semantic mapping. Large Language Models understand the concept of a "price", a "product description", or an "author name" based on the surrounding context. If a site moves the price from an <h1> tag to a <span class="text-gray-500"> embedded in a sidebar, a CSS selector fails. An LLM simply reads the text, identifies the currency symbol and context, and extracts the value.

The term "zero-shot" means the model requires no domain-specific fine-tuning. You provide the raw text from the web page and a strictly typed JSON schema. The model parses the context, identifies the variables, and outputs a structured JSON object matching your schema.

Processing the DOM for LLM Consumption

You cannot blindly send raw HTML payloads into an LLM context window. A standard e-commerce or real estate listing page contains massive amounts of non-content data. Inline CSS, base64 encoded tracking pixels, deeply nested SVG paths, and complex JavaScript bundles bloat the payload.

Sending raw HTML causes three critical failures in an extraction pipeline. First, it consumes an excessive number of tokens, driving up API costs unacceptably. Second, it increases inference latency. Third, and most importantly, it degrades the model's extraction accuracy. Large context windows suffer from the "lost in the middle" phenomenon. When you bury the actual product text inside thousands of lines of markup, the attention mechanism struggles to isolate the relevant entities.

Pipelines must sanitize the payload before inference. The standard procedure involves several aggressive pruning steps.

First, traverse the DOM and remove all <script>, <style>, <svg>, <canvas>, and <nav> tags. Strip all HTML comments.
Second, remove all HTML attributes except for href in links and src in images. Classes, IDs, and data attributes are useless noise for a semantic model.
Third, convert the remaining HTML tree into standard Markdown.

Markdown is the optimal format for LLM consumption. It preserves the structural hierarchy of the document. Headers (#, ##) represent distinct sections. Bullet points represent repetitive elements or feature lists. Tables map perfectly to Markdown syntax. An HTML payload of 2MB often reduces to 15KB of dense Markdown. This fits comfortably into standard context windows, minimizes cost, and focuses the model entirely on the semantic content.

Defining Deterministic Schemas

LLMs operate probabilistically, generating the most likely next token. Data pipelines, however, require deterministic inputs. Your database expects specific data types, not free-form text. To bridge this gap, you must constrain the model using strict output schemas.

Do not rely on natural language prompts like "Find the product details and format them as JSON." This guarantees brittle pipelines. Instead, use JSON Schema definitions to force the model into a rigid structure.

When designing schemas for extraction, property descriptions act as targeted prompt tuning. If a page lists both an "MSRP" and a "Current Sale Price", a schema field simply named price is ambiguous. The LLM might pick either one probabilistically. Providing a detailed description resolves the ambiguity.

Here is an example using Pydantic to define a precise schema in Python. Pydantic allows you to enforce types and export the definition directly to JSON Schema format.

```python title="models.py" {7-9}
from pydantic import BaseModel, Field
from typing import Optional

class ProductExtraction(BaseModel):
name: str = Field(description="The full title of the item")
currency: str = Field(description="The 3-letter ISO currency code, e.g., USD")
sale_price: float = Field(description="The current active price. Ignore MSRP or original price.")
is_in_stock: bool = Field(description="True if the item can be purchased immediately")
sku: Optional[str] = Field(default=None, description="The internal manufacturer part number")




The descriptive fields guide the model's attention mechanism. If the model encounters multiple numbers on the page, the instruction "Ignore MSRP" embedded in the schema description dictates the correct extraction path.

## Implementing the Extraction Pipeline

Building this infrastructure from scratch requires wiring together headless browser clusters, payload minification logic, and LLM API integrations. You can simplify this architecture using the AlterLab API, which handles the entire lifecycle in a single request. 

The API executes the JavaScript, bypasses any front-end protections, sanitizes the DOM, and runs the zero-shot extraction against your provided schema.

Here is how you implement the pipeline using the AlterLab [Python SDK](https://alterlab.io/web-scraping-api-python).



```python title="scraper.py" {11-13}

from models import ProductExtraction

client = alterlab.Client("YOUR_API_KEY")

response = client.scrape(
    "https://example-ecommerce-site.com/listing/9876",
    render_js=True,
    extract={
        "type": "cortex_ai",
        "schema": ProductExtraction.model_json_schema()
    }
)

print(json.dumps(response.extracted_data, indent=2))

For teams building internal tooling or using different language stacks, the same operation maps directly to standard REST calls.

```bash title="Terminal" {7-17}
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-ecommerce-site.com/listing/9876",
"render_js": true,
"extract": {
"type": "cortex_ai",
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"sale_price": {"type": "number"},
"is_in_stock": {"type": "boolean"}
},
"required": ["name", "sale_price"]
}
}
}'




<div data-infographic="try-it" data-url="https://example.com/sample-product" data-description="Test zero-shot schema extraction against a sample page"></div>

## Handling Dynamic Content and Infrastructure

Before the semantic extraction phase can occur, the pipeline must successfully retrieve the raw page payload. This is rarely a simple HTTP GET request.

Modern single-page applications heavily rely on client-side rendering. If you fetch the raw HTML source via a standard HTTP client, you receive a blank `<body>` and a large JavaScript bundle. You must introduce a headless browser phase to execute the JavaScript, wait for the network idle state, and construct the final DOM tree.

Furthermore, public data sources frequently deploy defensive systems to manage traffic. These systems challenge automated requests by analyzing TLS fingerprints, tracking IP reputation, or forcing JavaScript execution to solve transparent challenges. Building an in-house proxy rotator and browser cluster to handle this requires significant engineering overhead.

Utilizing an infrastructure layer with robust [anti-bot handling](https://alterlab.io/smart-rendering-api) abstracts this complexity. The system negotiates the underlying network requirements, solves rendering challenges, and returns the final HTML payload. The LLM extraction is only as good as the data it receives. Ensuring reliable delivery of the fully rendered public data is a prerequisite for zero-shot parsing.

## The Hybrid Approach: Combining DOM Parsing with LLMs

Zero-shot extraction is incredibly powerful, but running a large context window LLM on every single page of a 10,000-page daily scrape is computationally expensive. It introduces higher latency than local parsing and increases pipeline costs.

For high-volume pipelines, senior engineers deploy a hybrid architecture. They utilize standard DOM parsing tools for stable, high-level structural navigation, and reserve LLM extraction for the volatile inner components.

Consider scraping a directory page containing 50 individual listing cards. Instead of passing the massive directory HTML to the LLM and asking it to extract an array of 50 objects, you isolate the cards first.

Use a standard CSS selector to grab the array of nodes: `document.querySelectorAll('.grid-item')`. The container structure of a grid rarely changes. 
Then, iterate over the resulting nodes. Pass the highly targeted, minimal HTML of the individual card to the LLM for schema extraction. 

This hybrid model drastically reduces the token count. It increases inference speed. It prevents the model from truncating output arrays due to context limits. Most importantly, it maintains resilience against the most fragile part of the UI: the deeply nested component structure where prices, badges, and metadata reside.

## Handling Pagination and Arrays

When you do need to extract arrays directly via the LLM, schema design becomes slightly more complex. You must wrap your object definition inside an array type.

When extracting lists, LLMs occasionally suffer from output truncation. If a page has 100 items, the model might extract 45 items and hit its output token limit, returning an incomplete JSON string. 

To mitigate this in pure zero-shot setups, you must manage pagination explicitly. Instruct the LLM to identify pagination links. Extract a smaller batch of items per request, detect the "Next Page" URL semantically, and trigger subsequent scraping jobs. For detailed schema definitions on array handling, refer to the [API docs](https://alterlab.io/docs) which provide examples of nested object validation.

## Production Considerations and Error Handling

Even with strict schemas, LLMs can hallucinate or fail to map a specific edge-case string to a required data type. Production pipelines require robust fallback mechanisms.

Implement strict validation layers immediately after the extraction phase. If the JSON response fails validation (e.g., a required field is missing or a string is returned instead of a float), catch the error. The standard protocol is to trigger an immediate retry with an adjusted prompt, feeding the validation error back to the model as context. "You returned 'Sold Out' for sale_price. Ensure sale_price is a float or null."

You must also account for the economics of inference. Calculate the token cost per page. Compare the ongoing compute cost against the engineering hours spent maintaining static CSS selectors. For dynamic sites that change layouts weekly, the compute cost of LLM extraction is vastly cheaper than the human cost of script maintenance. For static, legacy sites that haven't changed in five years, standard CSS selectors remain the optimal choice.

## Conclusion

Agentic web scraping replaces hardcoded rules with semantic understanding. By converting bloated DOMs into minified Markdown and applying strict JSON schemas, data engineering teams can build extraction pipelines that automatically adapt to UI changes. Zero-shot JSON extraction eliminates the maintenance trap of fragile CSS selectors, allowing teams to focus on scaling data ingestion rather than fixing broken scripts.