Shadow DOM, iframes and nested documents in extraction

The selector that finds nothing on a visible page

The price is right there on the screen. You inspect it in DevTools, see a tidy span with a sensible class, write the selector, run it in your collector and get nothing. Not a wrong value, not a timeout. An empty result, on a page you can see with your own eyes.

When the selector is correct and the page has clearly loaded, the usual explanation is structural. The element you’re pointing at lives somewhere your code never searches: inside a second document, or a separate tree attached to an element, or a string of markup stored inside the page that only becomes elements later. DevTools shows all of these in one continuous tree, which is exactly why the bug is confusing. The inspector stitches together things your parser sees as separate or doesn’t see at all.

This piece covers the three common versions of that problem: shadow DOM, iframes, and markup nested inside other markup. For each one, it explains what’s actually happening in the browser, what a Playwright collector can reach, what a plain HTTP client with a parser can reach, and what neither can.

It sits next to other pieces in this series without repeating them. The headless-versus-HTTP guide decides whether you need a browser. The selectors guide covers writing selectors that survive change. The hidden-API guide is about finding the data source behind a page. Here the question is narrower and more annoying: the data is in the page, you know where, and your code still can’t see it.

We hit these in production collectors regularly, mostly on retail sites built from component libraries and on pages that embed third-party widgets. The fixes are rarely hard once you know which of the three you’re dealing with. Most of the lost time goes into not knowing.

Three ways a document hides inside another

It helps to name the three shapes before getting into each one.

A shadow root is a separate tree of nodes attached to an ordinary element, called the host. The host sits in the normal document. Its shadow tree hangs off it and is rendered as if it were the host’s content, but it’s deliberately kept apart from the main document so that styles and scripts inside a component don’t leak out and page styles don’t leak in. Ordinary document queries stop at the boundary.

An iframe is a whole separate document, with its own URL, its own DOM, its own JavaScript context and, often, its own origin. The parent page contains only the iframe element pointing at it. Everything inside is loaded and rendered independently.

Nested markup is HTML that lives inside the page as something other than elements: the contents of a template tag, a script tag with a non-JavaScript type holding an HTML fragment, HTML escaped into a JSON blob or a data attribute, or the srcdoc attribute of an iframe. To the parser, it’s text or an inert fragment. It becomes real elements only when the page’s own JavaScript decides to use it.

The first two are mostly problems for browser-based collectors that don’t know where to look. The third is mostly a problem for HTTP-based collectors, and it’s often good news in disguise, because the data is sitting in the raw response and just needs a second parse.

The diagnostic question for any empty selector is which of these the element lives in. DevTools answers it quickly if you know the signs: a #shadow-root line above the element, a #document line inside an iframe node, or no element at all in the raw page source even though the rendered tree shows it.

How shadow DOM works in the browser

A page creates a shadow root by calling attachShadow() on an element, passing a mode of either open or closed. Component frameworks and design systems do this constantly. A custom element like <product-price> attaches a root, fills it with its own markup and styles, and the browser renders that markup where the element sits.

The mode matters. With an open root, the page’s own JavaScript can reach inside through the host’s shadowRoot property. With a closed root, that property returns null, and only the code that created the root keeps a reference to it. Closed mode exists so a component can keep its internals private from the rest of the page.

Queries respect the boundary either way. document.querySelector and querySelectorAll search the main document and don’t descend into shadow roots. You have to get the root first and query it separately, and if that root contains another component with its own root, you repeat the step. A deeply componentised page can nest several levels.

Slots complicate the picture helpfully. A component can declare slot elements in its shadow tree, and the host’s ordinary children get projected into those slots when rendering. Those children are still in the light DOM, the normal document, even though they appear on screen inside the component. So a product card component might hold the title as a slotted child, visible to any ordinary selector, while the price is generated inside the shadow tree and invisible to them.

That’s why a single page can behave inconsistently. Some fields extract fine because they’re slotted light-DOM content. Others vanish because the component generates them inside its root. When half a record extracts and half doesn’t, shadow DOM is a strong suspect.

In DevTools, shadow roots show up as a #shadow-root (open) or #shadow-root (closed) line under the host element. That label tells you both where the element lives and which mode you’re facing.

Why page.content() and your parser miss it

A common collector pattern is to render the page in a browser, grab the full HTML with page.content(), and hand that string to BeautifulSoup, lxml or selectolax. It’s a sensible split: the browser runs the JavaScript, and a fast parser does extraction. It also silently drops every shadow tree on the page.

The reason is serialisation. page.content() returns the document serialised as HTML, the same thing outerHTML gives you on the root element, and shadow roots aren’t part of that serialisation by default. The output includes the host element, <product-price> with its attributes, and nothing inside it. Your parser receives a document in which the component is an empty tag.

Current browsers have a newer getHTML() method on elements that can include shadow roots when asked, either the ones marked serialisable when they were created or ones you pass in explicitly. That’s useful where it applies, but it depends on the browser version and on how the site created its roots, so you can’t rely on it across targets. Checking it in page.evaluate() on one page of each target tells you quickly whether it helps.

Parsers working on raw HTTP responses face a more basic problem. If the shadow tree is built by JavaScript at runtime, it doesn’t exist in the response at all. The raw HTML contains the host tag, maybe some attributes, and the script that will fill it in. No parser can extract what was never sent.

So the fix depends on which pipeline you run. In a browser collector, extract inside the browser, where the shadow trees exist, instead of serialising first. In an HTTP collector, find where the component gets its data, which is usually somewhere you can fetch directly. Both are covered below.

Reaching open shadow roots from Playwright

Playwright handles open shadow DOM better than most people expect. Its locators pierce open shadow roots by default. page.locator("product-price .amount"), get_by_text, get_by_role and the other built-in locators search through open roots as if the boundaries weren’t there, including roots nested inside other roots. For most componentised pages, switching from “serialise then parse” to “extract with locators” is the entire fix.

There’s one documented exception that catches people: XPath doesn’t pierce shadow roots. An XPath locator in Playwright searches only the light DOM. If your collector was built on XPath because that’s what the parser used, those selectors will keep returning nothing inside components even in a live browser. Rewrite those fields as CSS or role-based locators.

For bulk extraction, where calling a locator per field on every page is slow, you can do the walking yourself in one page.evaluate() call. A short function that visits every element, checks for a shadowRoot, and recurses into it can collect the text or attributes you need from all open roots and return one plain object to Python. That keeps the number of round trips between Python and the browser low, which matters when you’re extracting dozens of fields from thousands of pages.

A related approach, when you do want a fast offline parser, is to have that same evaluate function flatten the page: walk the tree, and wherever it finds an open root, serialise the root’s contents into the output inside the host element. You get one HTML string with the shadow content inlined, which any parser can then query. It’s a custom serialiser, so test it against the rendered page before trusting it, and keep in mind that the flattened document no longer matches either the raw response or the live DOM exactly.

Whichever route you take, remember that shadow content is rendered by JavaScript, so wait for the component to finish before extracting. A locator with an expectation, such as waiting for the price element to have non-empty text, is more reliable than a fixed sleep.

Closed roots and what nothing can reach

Closed shadow roots are the hard stop. Playwright’s documentation states plainly that closed-mode shadow roots aren’t supported by its locators. Page JavaScript can’t reach them either, because shadowRoot returns null. The component that created the root holds the only reference.

You’ll see techniques discussed that patch attachShadow before the page’s scripts run so every root is forced open. We don’t use them. They change how the page’s components behave, which means the page you’re extracting from is no longer the page the site serves, and they can break components that rely on their internals being private. Some sites also use closed roots for security-sensitive widgets, including challenge and verification components, and interfering with those is the kind of thing this site doesn’t publish instructions for.

The practical question with a closed root is whether the data inside it is available any other way. Often it is. A component displaying a price had to get that price from somewhere: an attribute on the host element, a JSON blob in the page, or an API call the component made after load. The rendered text in a closed root is the last stop in that chain, and the earlier stops are usually reachable.

Look at the host element’s attributes first. Component libraries commonly pass data in as attributes, so <product-price value="1299" currency="SGD"> carries the number in the light DOM where any selector finds it. Then check the network panel for the request the component makes, and check the page source for embedded state.

If none of those exist and the data only ever appears as rendered text inside a closed root, treat that as information about what the site intends. It isn’t a common situation, and when we meet it we usually talk to the client about whether that field is worth collecting at all.

Declarative shadow DOM in the raw response

There’s a newer way to create shadow roots that changes the story for HTTP collectors. Declarative shadow DOM lets a server send the shadow tree inside the HTML itself, wrapped in a template element with a shadowrootmode attribute set to open or closed. When a current browser parses that template, it attaches a shadow root to the parent element and moves the template’s contents into it, with no JavaScript needed.

Sites use it for server-side rendering of components, because it lets a component’s markup show up on first paint instead of after scripts run. For a collector, it means the content is in the raw HTTP response, which is good news. The catch is where your parser puts it.

A browser consumes the template and builds a shadow root. A Python HTML parser doesn’t build shadow roots at all, so the template stays a template. What happens to its contents depends on the parser. Some parsers treat template contents as a separate fragment that isn’t part of the normal child list, so ordinary selectors don’t descend into it. Others leave the children in the tree like any other element. The only way to know for your parser is to try it on a real page from the target.

If your selectors miss content you can see inside a template shadowrootmode block in the raw source, select the template element itself, take its inner HTML as a string, and parse that string as its own document. It’s two steps instead of one, and it works in any parser.

It’s worth checking whether a target uses declarative shadow DOM before deciding it needs a browser. A page that looks JavaScript-rendered in DevTools may be sending the full component markup in its response, in which case a plain HTTP client with a second parse gets everything, far more cheaply.

Going around the component to its data

The most durable fix for shadow DOM is often not to extract from the component at all.

Components are presentation. The data they display comes from somewhere else, and that somewhere is usually more stable than the component’s internal markup, which a front-end team can rewrite in any release without the page looking different. Four places to look, roughly in the order we check them.

Host attributes. As above, many components receive their data as attributes on the custom element. These are in the light DOM, in the raw response when server-rendered, and easy to select.

Embedded page state. Frameworks that render on the server often embed the state they rendered from, as a JSON object in a script tag, so the client can take over without refetching. That object frequently contains every field on the page in structured form. Searching the raw response for a known value, such as the exact price you can see, finds it fast.

Structured data. Product pages often carry JSON-LD for search engines, with name, price, availability and identifiers in a documented schema. It’s outside any component and designed to be machine-read.

The component’s own requests. If the component fetches its data after load, the network panel shows the call. That’s the hidden-API route, covered in its own guide, and it usually replaces the browser for that field entirely.

Only when all four come up empty does it make sense to extract from inside shadow trees, and at that point Playwright locators are the tool. Check all four first. When one of them has the data, the collector ends up cheaper and less fragile than one that reads rendered text from inside components.

Iframes are separate documents

Iframes are a different animal. An iframe sits entirely outside the parent’s DOM. Each one is a browsing context with its own document, loaded from its own URL, with its own scripts running in their own global scope. The parent page holds an iframe element with a src attribute, and that’s all.

When you serialise the parent page, whether from a browser or by fetching it with an HTTP client, you get the iframe element and its attributes. None of the framed document’s content is included, because it was never part of the parent. Selectors against the parent can’t find anything inside the frame, in any tool.

Origin decides what the parent page’s own JavaScript can do. A same-origin frame, one served from the same scheme, host and port as the parent, can be reached from parent scripts through the frame’s contentDocument. A cross-origin frame can’t. The browser’s same-origin policy blocks the parent from reading the framed document, and contentDocument comes back as null. That’s a core security boundary of the web, and it’s why a page can embed a payment form from a processor without being able to read the card number typed into it.

Collectors aren’t page scripts, though, and that distinction is what makes frames reachable. Browser automation tools drive the browser from outside, through its debugging protocol, and can attach to every frame the browser loads, same-origin or not. A plain HTTP client, meanwhile, can simply request the frame’s URL as its own page.

So iframes are rarely a dead end. The work is recognising that the data is in a frame, finding which frame, and addressing it directly instead of searching the parent.

Frames are also common in exactly the places collectors go looking: embedded review widgets, store locators, price comparison panels, booking engines, and product configurators supplied by third parties. When a whole section of a page refuses to extract, check whether that section is a frame before anything else.

Frames in Playwright

Playwright models every frame explicitly. page.main_frame is the top document, page.frames lists every frame currently attached, and each frame object has its own url, name, locator() and evaluate(). You can find a frame by name or URL with page.frame(name=...) or page.frame(url=...), or build a frame_locator that selects the iframe element in the parent and then locates inside it.

frame_locator is the one to reach for first. page.frame_locator("iframe#reviews").locator(".rating") finds the iframe, waits for it, and searches inside it, with the same auto-waiting as any other locator. Frame locators chain, so a frame inside a frame is one more frame_locator call. Because Playwright drives the browser from outside, this works on cross-origin frames too.

Frames have their own lifecycle, which trips up collectors written for single documents. A frame loads after the parent, sometimes long after, because the parent’s scripts create it or lazy-load it when scrolled into view. A frame can navigate on its own, detach and be replaced by a new one, or reload while you’re extracting. Holding on to a frame object across those changes gives you errors about detached frames. Locators re-resolve each time they’re used, which is one more reason to prefer them over stored frame handles.

Lazy-loaded frames are a particular trap. If the reviews iframe only gets its src once it scrolls into view, it doesn’t exist on a page that never scrolls, and page.frames won’t list it. The fix is to scroll the host element into view, or to wait for the frame locator’s content rather than for page load.

Finally, page.content() behaves the same way with frames as with shadow roots: it serialises only the main frame. If your pipeline renders and then parses offline, each frame’s content must be fetched separately with that frame’s own content() call, and you have to keep track of which frame each piece of HTML came from.

Frames with a plain HTTP client

An HTTP collector can’t use frame locators, but it has a simpler option: fetch the frame’s document directly. The parent’s HTML contains the iframe element with its src. Resolve that URL against the parent’s URL, request it, and parse the response as a page in its own right.

That works cleanly for a lot of frames, especially widgets whose src is a stable URL with a product ID in the query string. It fails in a few recognisable ways.

The src may be empty in the raw response and set by script later, possibly with parameters computed in the browser. Then you look in the page’s scripts or embedded state for how that URL is built, or you fall back to a browser for that one piece.

The URL may carry a short-lived token. Some embedded widgets sign their frame URLs, so a URL copied from yesterday’s page returns an error today. The token has to come from a fresh parent page each time, and if it’s tied to a session, from the same session.

The frame may expect context from its parent. Some framed applications check the Referer header, read parameters passed through the URL fragment, or wait for a postMessage from the parent before rendering anything. A frame fetched in isolation then returns an empty shell. A browser is the practical answer for those.

And frames with a srcdoc attribute have no URL at all. The framed document is the attribute’s value, HTML-escaped. Unescape it and parse it as its own document. That’s the easiest frame to extract from once you know to look at the attribute instead of for a URL.

One more thing people mix up. X-Frame-Options and the Content Security Policy frame-ancestors directive control which sites may embed a page in a frame. They don’t stop a client from requesting that page directly, and they’re not a signal about fetching. Terms of use and the data’s owner are.

Markup hiding inside markup

The third shape is HTML stored as something other than elements. It’s the one HTTP collectors most often miss, and the one where the data is most often sitting in the response already.

template elements hold inert fragments that scripts clone into the page later. As with declarative shadow DOM, what your parser does with template contents varies. If selectors miss content you can see in the source, take the template’s inner HTML and parse it separately.

script tags with types like text/template or text/x-template hold HTML fragments for client-side templating. Parsers treat script contents as raw text, as they should, so none of it becomes elements. The fragment often contains placeholders rather than data, which makes it less useful, but occasionally it’s the only place a piece of static text lives.

JSON blobs and data attributes sometimes carry escaped HTML: a product description stored as a string with its own markup, or a data-content attribute holding the HTML for a tooltip or tab panel. Parse the JSON or read the attribute, unescape, and parse the result as a fragment. Product descriptions in embedded state are a common example, and they’re often cleaner than the rendered version.

noscript content is a special case. Browsers with scripting on treat it as raw text. Parsers without a scripting mode may treat it as normal markup and give you elements that a browser would never render. That occasionally means a parser finds a fallback image or link a browser user never sees, which is fine as long as you know that’s where it came from.

The general rule: when a field is visible in the raw response as text, but your selector can’t reach it as an element, look at what it’s nested inside. If it’s inside a string, an attribute, a template or a script, it needs a second parse.

Frames and roots worth leaving alone

Not every nested document is something a collector should be inside, and knowing which to skip saves time and trouble.

Payment frames from processors are isolated precisely so that the host page can’t read them. There’s nothing in them a legitimate collector needs, and they sit close to card data you should never be handling.

Verification and challenge widgets commonly load in their own frames or closed components. They’re the site’s defence, and interacting with them programmatically is outside what we’ll describe here. If a page shows one to your collector, that’s a signal about how the site views automated access, and it deserves a decision about the target rather than a workaround.

Consent and login frames from identity providers exist to handle credentials and consent on the provider’s origin. A collector working with an account it owns may need to complete a login flow, but should never be extracting from inside another party’s identity frame.

Third-party review and comment widgets are a judgement call. The data belongs to the widget provider as much as to the site, it may include personal data about reviewers, and the provider’s terms can differ from the site’s. Collect aggregate figures like rating and count where you have a basis to, and be careful with anything tied to individuals.

Advertising frames are noise. Block them, as the bandwidth guide in this series describes, and move on.

What to do on Monday

When a selector returns nothing on a page that visibly contains the data, run this checklist before rewriting anything.

Open DevTools on the element and read the tree above it. A #shadow-root line means shadow DOM, and the label tells you open or closed. A #document line inside an iframe means a frame. If neither appears, view the raw page source and search for the value. If it’s there inside a template, script, attribute or JSON string, it’s nested markup.

For open shadow roots in a browser collector, replace serialise-then-parse with Playwright CSS or role locators, and rewrite any XPath for those fields. For bulk extraction, walk the roots in one evaluate() call.

For shadow content in an HTTP collector, check for declarative shadow DOM in the response, then for host attributes, embedded state, JSON-LD and the component’s own API call, in that order.

For closed roots, go straight to those same four data sources. If none has the field, reconsider whether to collect it.

For iframes in a browser, use frame_locator, wait for the frame’s content, and scroll lazy frames into view. In an HTTP collector, fetch the src directly, unescape srcdoc, and watch for tokens and parent-dependent frames that need a browser.

For nested markup, extract the string and parse it a second time.

Then add the page to your saved-page test suite with a note on which shape it was. The next redesign that moves a field into a component will look familiar.

For more on the parsing, rendering and data-source questions around production collectors, the full set of guides is at Data Research Tools.

Get new guides and videos first — join the Telegram channel.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *