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

推荐订阅源

GbyAI
GbyAI
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Microsoft Security Blog
Microsoft Security Blog
S
SegmentFault 最新的问题
Y
Y Combinator Blog
Google DeepMind News
Google DeepMind News
Last Week in AI
Last Week in AI
博客园 - 聂微东
Attack and Defense Labs
Attack and Defense Labs
T
Tailwind CSS Blog
阮一峰的网络日志
阮一峰的网络日志
月光博客
月光博客
SecWiki News
SecWiki News
Microsoft Azure Blog
Microsoft Azure Blog
小众软件
小众软件
S
Secure Thoughts
C
Check Point Blog
WordPress大学
WordPress大学
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Google Online Security Blog
Google Online Security Blog
MongoDB | Blog
MongoDB | Blog
Schneier on Security
Schneier on Security
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Spread Privacy
Spread Privacy
IT之家
IT之家
美团技术团队
罗磊的独立博客
Google DeepMind News
Google DeepMind News
博客园 - 叶小钗
Recent Announcements
Recent Announcements
云风的 BLOG
云风的 BLOG
V
Vulnerabilities – Threatpost
Security Latest
Security Latest
博客园 - 司徒正美
Cyberwarzone
Cyberwarzone
C
CERT Recently Published Vulnerability Notes
TaoSecurity Blog
TaoSecurity Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
V2EX - 技术
V2EX - 技术
Vercel News
Vercel News
有赞技术团队
有赞技术团队
J
Java Code Geeks
博客园 - 【当耐特】
Project Zero
Project Zero
NISL@THU
NISL@THU
P
Privacy & Cybersecurity Law Blog
The Last Watchdog
The Last Watchdog
aimingoo的专栏
aimingoo的专栏
S
Securelist
The Cloudflare Blog

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
Handling Shadow DOMs in Agentic Scraping Workflows
AlterLab · 2026-06-16 · via DEV Community

TL;DR

Web components encapsulate UI and data inside Shadow DOMs, hiding it from standard parsers like BeautifulSoup and document.querySelector. To extract this data, you must use browser automation APIs to pierce the shadow root, execute recursive JavaScript traversal, or leverage an AI-driven extraction API that interprets the fully rendered visual layer instead of the raw DOM structure.

The Shadow DOM Problem

Traditional web scraping relies on a predictable, global DOM tree. You fetch the HTML, parse it, and write CSS selectors to extract text attributes. Web Components broke this paradigm.

The Shadow DOM allows developers to encapsulate DOM subtrees and CSS styles. When a modern web application mounts a custom component, it attaches a #shadow-root to a regular DOM element (the host). Anything inside that shadow root is invisible to standard global queries.

If you run document.querySelectorAll('span.price') on a modern e-commerce site, you will often get an empty node list, even if the price is plainly visible on the screen. The element exists, but it is locked inside a shadow root.

For data engineers building automated collection pipelines, this introduces severe friction. Agents fed raw HTML payloads will hallucinate or fail because the target data literally does not exist in the source document they are reading. The data is either injected via client-side JavaScript post-load or hidden behind a shadow boundary.

Open vs. Closed Shadow Roots

Before writing traversal logic, you need to understand the two modes of shadow roots.

When developers create a shadow root, they define its mode:

```javascript title="shadow_creation.js" {2-3}
const host = document.querySelector('#pricing-widget');
// Open mode: Accessible via host.shadowRoot
const openRoot = host.attachShadow({ mode: 'open' });

// Closed mode: host.shadowRoot returns null
const closedRoot = host.attachShadow({ mode: 'closed' });




**Open Shadow Roots** are common. You can access the internal DOM tree through the `shadowRoot` property of the host element. While standard CSS selectors won't pierce the boundary from the outside, you can write JavaScript to step inside the boundary and run a new query.

**Closed Shadow Roots** return `null` when you try to access `host.shadowRoot`. They are designed to completely restrict external JavaScript access. Piercing a closed shadow root requires intercepting the `attachShadow` prototype or using Chrome DevTools Protocol (CDP) debugging APIs via headless browsers.

## Recursive JavaScript Traversal

To scrape data hidden in open shadow roots, your scraping agent must execute JavaScript inside the browser context. Standard outerHTML extraction is insufficient.

You need a script that recursively walks the DOM tree, identifies elements with shadow roots, and pulls their internal HTML into a flat structure that your parsing logic can actually read.



```javascript title="shadow_traversal.js" {10-14}
function expandShadowDOM(element = document.body) {
  let result = element.cloneNode(false);

  // If the element has a shadow root, traverse inside it
  if (element.shadowRoot) {
    const shadowContainer = document.createElement('div');
    shadowContainer.setAttribute('data-shadow-host', 'true');

    element.shadowRoot.childNodes.forEach(child => {
      shadowContainer.appendChild(expandShadowDOM(child));
    });

    result.appendChild(shadowContainer);
  }

  // Traverse normal light DOM children
  element.childNodes.forEach(child => {
    result.appendChild(expandShadowDOM(child));
  });

  return result;
}

// Execute this in your browser automation script
const flatDOM = expandShadowDOM();
console.log(flatDOM.innerHTML);

This approach works for simple pages but creates massive performance bottlenecks on complex Single Page Applications (SPAs). Every nested component requires recursive DOM cloning. When dealing with hundreds of web components, the memory overhead scales poorly.

Native Headless Browser Support

If you manage your own browser infrastructure, tools like Playwright provide native support for piercing open shadow roots.

Playwright's selector engine automatically pierces open shadow roots by default. You do not need to write recursive JavaScript traversal if you know the exact selector of the hidden element.

```python title="playwright_scraper.py" {7-8}
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto("https://example-directory.com/profiles")

# Playwright automatically pierces the shadow DOM to find this selector
prices = page.locator('.internal-price-node').all_inner_texts()

print(prices)
browser.close()




While Playwright simplifies selector targeting, it forces you to run and maintain a headless browser cluster. You have to handle proxy rotation, session management, and Chromium memory leaks. Add in modern bot protection mechanisms, and maintaining this cluster becomes a full-time engineering effort. You can read more about comprehensive [bot detection handling](https://alterlab.io/smart-rendering-api) to understand the infrastructure requirements.

## Context Window Limitations in Agentic Scraping

Agentic scraping workflows—where LLMs are used to navigate sites and extract unstructured data—suffer heavily from Web Components.

LLMs have finite context windows. Feeding an entire HTML document into an LLM is already token-heavy. When you flatten a shadow DOM using the recursive JavaScript method above, you multiply the token count. Web components often wrap simple data in layers of `<template>`, `<slot>`, and custom framework-specific div containers. 

Instead of passing HTML to an LLM, the optimal agentic workflow skips the DOM entirely. 

<div data-infographic="try-it" data-url="https://example-directory.com" data-description="Test extraction on a page with shadow components"></div>

## Bypassing the DOM with Cortex AI

Rather than wrestling with recursive JavaScript, nested selectors, or Playwright infrastructure, you can offload the entire extraction step. 

AlterLab uses Cortex AI to read the visual representation of the fully rendered page. It ignores the difference between the light DOM and the shadow DOM. If the data renders on the screen, Cortex AI extracts it. 

<div data-infographic="steps">
  <div data-step data-number="1" data-title="Send Request" data-description="Pass the URL and an extraction prompt to the AlterLab API."></div>
  <div data-step data-number="2" data-title="Cloud Rendering" data-description="The API handles proxies, bypasses captchas, and fully renders the page (including Web Components)."></div>
  <div data-step data-number="3" data-title="AI Extraction" data-description="Cortex AI reads the rendered layer and returns clean JSON."></div>
</div>

This requires exactly one API call. You dictate the required schema, and the engine handles the underlying rendering and traversal. 

Here is how you execute this using the official [Python SDK](https://alterlab.io/web-scraping-api-python).



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

client = alterlab.Client("YOUR_API_KEY")

response = client.scrape(
    "https://example-real-estate.com/listings", 
    cortex_prompt="Extract property names, addresses, and prices as a list of objects.",
    formats=["json"]
)

print(response.json)

The formats=["json"] parameter ensures the output is instantly usable in your downstream data pipelines. The AI agent handling the extraction operates on the server side, abstracting away the complex token management and DOM traversal logic.

For environments where Python is not available, you can utilize the REST API directly. Below is the equivalent implementation using cURL. See the full API reference for advanced configuration options like webhooks and scheduling.

```bash title="Terminal" {4-6}
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-real-estate.com/listings",
"cortex_prompt": "Extract property names, addresses, and prices as a list of objects.",
"formats": ["json"]
}'




Both examples accomplish the exact same outcome: they bypass the need to understand the target site's component architecture. Whether the developers used React, Vue, native Web Components, or complex shadow roots, the extraction pipeline remains identical.

## Takeaways

Web Components and Shadow DOMs intentionally obscure data from standard web scraping techniques. While standard parsers fail immediately, you have multiple paths forward.

You can write custom recursive JavaScript to flatten the DOM structure, though this scales poorly on heavy applications. You can manage a headless Playwright cluster to utilize native shadow-piercing selectors, which requires maintaining extensive infrastructure. 

For the most resilient data pipelines, particularly in agentic workflows, decoupling your extraction logic from the underlying DOM structure is the best path forward. By relying on visual rendering and AI extraction models, your scrapers become immune to front-end refactors and complex component hierarchies.