How to Scrape Data Inside iFrames (2026 Guide)
Learn how to scrape data inside iframes: grab the frame src and fetch it directly, or drive cross-origin frames with Playwright and Selenium. Real code.

To scrape data inside iframes, you have to stop treating the page as one document. You can see the price, the review, or the chart sitting right there, but your scraper's HTML doesn't contain a single character of it, because that content lives inside an : a separate document with its own DOM, its own URL, and its own origin. This guide covers the two approaches that reliably work, when each one applies, and real frame handling code for Playwright, Selenium, and SparkProxy's Scraping API, including the fastest move most tutorials skip: request the frame's src directly and drop the browser entirely.
Why iFrame Content Is Not in the Parent DOM
An is a full HTML document embedded inside another one. It gets its own window, its own document, its own DOM tree, and usually its own URL. The parent page holds only the tag itself:
<iframe id="pricing-widget" src="https://widgets.sparkproxy.io/pricing/embed?plan=pro"></iframe>
That tag is all a plain HTTP request ever sees. When you run requests.get(page_url).text or call document.querySelector(".plan-price") from the parent, you get the element, not the price rendered inside it. The child document was fetched by the browser as a second request, and its nodes belong to a separate DOM the parent never merges in.
Browsers do expose a bridge: iframe.contentWindow and iframe.contentDocument let parent JavaScript reach into the child. But that bridge is governed by the same-origin policy, so it slams shut the moment the child comes from a different origin. This single fact explains almost every failed iframe scrape. Your selector is correct, the element is visible, and your code still returns nothing, because it is looking in the wrong document.
The mental model that fixes this: an iframe is a second page. Find its URL and scrape that page, or point your automation tool at the child document explicitly. Everything below is a variation on those two ideas.
Same-Origin vs Cross-Origin Frames
An origin is the triple of scheme, host, and port. https://www.sparkproxy.io and https://widgets.sparkproxy.io are different origins because the host differs. That difference decides which techniques are available to you.
With a same-origin frame, parent-page JavaScript can freely read iframe.contentDocument, so even a quick page.evaluate can pull data out. With a cross-origin frame, the browser throws a SecurityError the instant you touch contentDocument, which is why so many people conclude, wrongly, that cross-origin iframes cannot be scraped.
They can. The trick is knowing which layer you are working at:
| Capability | Same-origin frame | Cross-origin frame |
|---|---|---|
| Parent-page JS reads the frame DOM (`contentDocument`) | Yes | No (`SecurityError`) |
| Selenium `switch_to.frame` | Yes | Yes |
| Playwright `frame_locator` / `page.frames` | Yes | Yes |
| Direct HTTP fetch of the frame `src` | Yes | Yes |
The key insight competitors gloss over: switch_to.frame and frame_locator operate at the browser automation protocol level, not through page JavaScript, so they cross origin boundaries without complaint. The same-origin policy only restricts one thing, in-page script access. Your automation driver is not a page script. Neither is a server-side HTTP request. So two of your four options ignore the cross-origin wall entirely.
Scraping at scale? Skip the blocks.
Fast, unblockable datacentre proxies with unlimited bandwidth.
First Move: Find the iFrame src
Before writing any scraping code, look at the frame. Right-click the region you want, choose Inspect, and find the node in the elements panel. Read its src. That one attribute tells you which approach to reach for.
You can also enumerate frames programmatically. In Playwright:
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto("https://www.sparkproxy.io/pricing", wait_until="networkidle")
for frame in page.frames:
print(repr(frame.name), frame.url)
browser.close()
That prints every frame's URL, including nested ones. Now classify what you see:
| `src` value | What it means | How to scrape it |
|---|---|---|
| `https://...` (a real URL) | A genuine second document | Fetch the `src` directly, or use `frame_locator` |
| `srcdoc="..."` | Inline HTML held in the attribute | Parse the parent, unescape the `srcdoc` value |
| `about:blank` | Content written by JS after load | Browser only (`frame_locator` / `switch_to`) |
| `blob:...` or `data:...` | Generated client-side | Browser, or decode the `data:` URI yourself |
Roughly 80% of real-world iframes fall in the first row. Analytics dashboards, pricing widgets, comment systems, embedded maps, and video players nearly always point at a real URL. That URL is your shortcut.
The Fastest Way to Scrape Data Inside iFrames: Fetch the src Directly
Here is the move most guides never mention. The frame's src is a normal URL. You can request it directly and skip the parent page, the browser, and every frame boundary in one step. No switch_to, no frame_locator, no headless Chrome. It is faster, cheaper, and far easier to maintain.
Copy the src verbatim, keeping any query string, then send it through the SparkProxy Scraping API:
import requests
API = "https://scrape.sparkproxy.io/api/v1"
API_KEY = "YOUR_SPARKPROXY_KEY"
# The iframe's src, copied exactly from the parent page (keep any ?token=... query)
iframe_src = "https://widgets.sparkproxy.io/pricing/embed?plan=pro"
resp = requests.post(
API,
headers={"X-API-Key": API_KEY},
json={
"url": iframe_src,
"render_js": False, # a static frame document costs 1 credit
"format": "html",
"forward_headers": {
# Many embedded widgets return 403 or a blank body without a matching Referer
"Referer": "https://www.sparkproxy.io/pricing"
},
},
timeout=60,
)
resp.raise_for_status()
html = resp.text
Then parse the returned document like any other page:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, "html.parser")
price = soup.select_one(".plan-price").get_text(strip=True)
print(price)
The same request in curl:
curl -X POST "https://scrape.sparkproxy.io/api/v1" \
-H "X-API-Key: $SPARKPROXY_KEY" \
-H "Content-Type: application/json" \
-d '{
"url": "https://widgets.sparkproxy.io/pricing/embed?plan=pro",
"render_js": false,
"format": "html",
"forward_headers": { "Referer": "https://www.sparkproxy.io/pricing" }
}'
Two details make or break this approach:
The Referer gate. Plenty of widgets check the Referer header and refuse to serve their content unless the request looks like it came from the page that embeds them. Set it with forward_headers (as above) so the header matches the embedding URL. If the widget also depends on a session, pass the relevant cookies too.
X-Frame-Options and CSP do not stop you. A widget that sends X-Frame-Options: DENY or Content-Security-Policy: frame-ancestors 'none' cannot be rendered inside a browser frame on a page it does not approve. Those headers govern browser rendering only. A raw server-side GET never asks a browser to frame anything, so it reads the response body regardless. Direct-fetching the src sidesteps the entire anti-embedding mechanism.
There is a bonus effect worth naming: requesting the src directly collapses the frame boundary. The document that used to be trapped inside an iframe becomes your top-level response. Your selectors, your wait_for, and any js_scenario now target it without a single frame switch. That is why this path is both the simplest to write and the cheapest to run.
For the deeper mechanics of finding the real endpoint behind a widget, our guide on scraping hidden JSON API endpoints uses the same instinct: skip the rendered wrapper and hit the source.
When You Actually Need a Real Browser
Direct fetch is the default, but it does not cover everything. Reach for a browser (Playwright, Selenium, or the Scraping API with render_js) when any of these are true:
- The
srcisabout:blank,blob:, or missing, so there is no URL to request. - The frame's content is built by JavaScript after it loads, so a plain fetch returns an empty shell.
- The widget only renders after the parent establishes an authenticated session or posts a message to it.
- You need to interact inside the frame, for example clicking a tab, submitting a form, or paginating.
In those cases you drive the actual frame. The next two sections show the exact API in each tool.
Frame Handling in Playwright
Playwright has the cleanest frame model of any browser tool. The everyday API is frame_locator, which builds a locator scoped to a frame and works across origins:
page.goto("https://www.sparkproxy.io/pricing", wait_until="domcontentloaded")
widget = page.frame_locator("iframe#pricing-widget")
price = widget.locator(".plan-price").inner_text()
print(price)
frame_locator auto-waits, so you rarely need explicit sleeps. If you want the whole frame document as HTML, grab the Frame object through the element's content_frame():
handle = page.query_selector("iframe#pricing-widget")
frame = handle.content_frame() # a Frame, or None if it hasn't loaded
frame_html = frame.content() # full HTML of the child document
You can also select a frame by name or URL when it has no stable selector:
frame = page.frame(name="pricing")
# or match on the loaded URL:
frame = page.frame(url="**/pricing/embed**")
Use frame_locator for reading and clicking, and content_frame() when you want to hand the frame's HTML to a parser like selectolax or BeautifulSoup. If you are wiring proxies into a full Playwright run, our walkthrough on web scraping with Playwright and proxies covers launch args and rotation.
Frame Handling in Selenium
Selenium uses a stateful model: you switch the driver's focus into a frame, work there, then switch back. Forgetting the switch back is the most common bug in Selenium iframe code.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get("https://www.sparkproxy.io/pricing")
# Wait for the frame to exist, then move focus into it in one call
WebDriverWait(driver, 15).until(
EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, "iframe#pricing-widget"))
)
# Selectors now run inside the frame's document
price = driver.find_element(By.CSS_SELECTOR, ".plan-price").text
print(price)
driver.switch_to.default_content() # return to the parent document
switch_to.frame accepts three things: a numeric index, a name or id string, or a WebElement you already found. The frame_to_be_available_and_switch_to_it expected condition is the safest form, because it waits for the frame to load before switching, which kills the classic NoSuchFrameException race. When you are done, switch_to.default_content() returns you to the top document so later selectors do not silently fail. For a broader setup, see integrating proxies with Selenium.
Scraping Nested iFrames
Frames can hold frames. An embedded dashboard might load an iframe that itself loads a chart iframe. To reach the innermost data you traverse the chain one level at a time.
In Playwright, chain frame_locator calls:
cell = (
page.frame_locator("iframe#outer")
.frame_locator("iframe#inner")
.locator(".data-cell")
)
print(cell.all_inner_texts())
In Selenium, switch down through each level, and use parent_frame() to climb back up one step without resetting to the top:
driver.switch_to.default_content()
driver.switch_to.frame(driver.find_element(By.CSS_SELECTOR, "iframe#outer"))
driver.switch_to.frame(driver.find_element(By.CSS_SELECTOR, "iframe#inner"))
value = driver.find_element(By.CSS_SELECTOR, ".data-cell").text
driver.switch_to.parent_frame() # back up to #outer, not all the way out
The direct-fetch approach nests just as well, and often more cleanly. Fetch the outer src, find the inner inside that HTML, then fetch the inner URL. Two requests, no browser, no frame stack to manage.
srcdoc, about:blank, and blob Frames
Not every frame has a URL. Three special cases need different handling.
srcdoc frames. A srcdoc iframe carries its entire document inline, as an HTML-escaped attribute on the parent tag. There is nothing to fetch. Parse the parent HTML, read the srcdoc attribute, and unescape it:
import html as html_lib
from bs4 import BeautifulSoup
soup = BeautifulSoup(parent_html, "html.parser")
frame = soup.select_one("iframe[srcdoc]")
inner_markup = html_lib.unescape(frame["srcdoc"]) # turn <div> back into <div>
inner = BeautifulSoup(inner_markup, "html.parser")
print(inner.get_text(strip=True))
about:blank frames. Here the parent's JavaScript writes content into the frame after load, so there is no source URL and no static HTML to parse. This one requires a browser. Load the page, wait for the script to populate the frame, then read it with frame_locator or switch_to.frame.
blob and data frames. A blob: src is generated in the browser and cannot be requested from outside. A data: src, by contrast, embeds its payload right in the URL, so you can base64-decode it without any network call.
One more note on sandboxed frames. The sandbox attribute restricts what the frame can do inside a browser (run scripts, access same-origin storage, submit forms). It does not stop a server-side GET of the frame's src. If a sandboxed frame points at a real URL, direct fetch still works.
When render_js Is Required
render_js runs the target through a real headless browser. It costs more, so turn it on only when the content genuinely needs JavaScript. Static frame documents do not.
| Frame situation | `render_js` | Other params | Credits |
|---|---|---|---|
| Static HTML frame doc, real `src` | `false` | `forward_headers` (Referer) | 1 |
| JS-rendered frame content, real `src` | `true` | `wait_for`, `referrer` | 5 |
| Must click or paginate inside the content | `true` | `js_scenario` | 5 |
| Geo-locked widget | either | `country_code` | +5 |
| Widget needs a residential IP | either | `premium_proxy` | 10 (no JS) / 25 (JS) |
When the frame's own content is built by JavaScript, fetch its src with render_js and wait for a node that only appears after hydration. Because you loaded the frame document directly, that selector is top-level, no frame switching needed:
resp = requests.post(
API,
headers={"X-API-Key": API_KEY},
json={
"url": iframe_src,
"render_js": True, # frame content is built client-side, 5 credits
"wait_for": ".plan-price", # a node inside the frame document
"referrer": "https://www.sparkproxy.io/pricing",
},
timeout=90,
)
Note that the referrer parameter requires render_js to be on, which it is here. On the no-JS path you set the same header through forward_headers instead, as shown earlier. If your target is a heavy single-page app rather than a widget, our guide on scraping dynamic JavaScript websites goes deeper on wait strategies.
Common iFrame Errors and Fixes
| Symptom | Cause | Fix |
|---|---|---|
| `SecurityError: Blocked a frame with origin ... from accessing a cross-origin frame` | Reading `contentDocument` from parent-page JS | Use `switch_to.frame` / `frame_locator`, or fetch the `src` directly |
| `NoSuchFrameException` (Selenium) | Frame not loaded yet, or it reloaded | Wait with `frame_to_be_available_and_switch_to_it` before switching |
| Selectors return nothing after the page loads | Focus is still on the parent document | Call `switch_to.frame` first; return with `default_content()` |
| Blank body or HTTP 403 on a direct fetch | Widget requires a `Referer` (or cookie) | Set `forward_headers` Referer to the embedding URL; add `cookies` if needed |
| `StaleElementReferenceException` inside a frame | The frame navigated or re-rendered | Re-acquire the frame, then re-find the element |
| `frame_locator` finds nothing | Wrong selector, or the frame is `about:blank` | Confirm the `src`; if content is JS-injected, wait before reading |
A quick rule of thumb: cross-origin read errors mean you are at the wrong layer (drop to the automation API or a direct fetch), and empty results usually mean either the wrong document or a missing Referer.
Frequently asked questions
FAQ
Yes, whenever the frame has a real src URL, which most do. Copy that URL and request it directly through an HTTP client or the SparkProxy Scraping API. You skip the parent page and every frame boundary, and a static frame document costs a single credit with render_js off.
Because those elements live in a separate document, not the parent DOM your selectors default to. In Selenium you must call switch_to.frame before your find_element calls, and in Playwright you scope through frame_locator. Forgetting to switch back with switch_to.default_content() is the second most common cause of missing elements.
The browser blocks in-page JavaScript from reading a cross-origin frame's contentDocument, but that restriction does not apply to automation tools or server-side requests. Use frame_locator in Playwright or switch_to.frame in Selenium, both of which cross origins, or fetch the frame's src directly with a matching Referer header.
No. X-Frame-Options and the CSP frame-ancestors directive only tell a browser which pages may render the content in a frame. They do nothing to a raw server-side GET, since that request never asks a browser to frame anything. Fetching the src directly reads the response regardless of those headers.
Traverse the chain one level at a time. In Playwright, chain frame_locator("iframe#outer").frame_locator("iframe#inner"). In Selenium, switch_to.frame into the outer frame, then into the inner, and use switch_to.parent_frame() to step back up. With direct fetch, request the outer src, find the inner src in that HTML, and fetch it too.
Only when the frame's content is generated by JavaScript, or when you must interact with it. A static frame document parses fine with render_js off at one credit. Turn render_js on (and add wait_for) when a plain fetch returns an empty shell, or use js_scenario when you need to click or paginate inside the content.
Get 20% off your first month
Premium datacentre proxies with unlimited bandwidth. Use the code at checkout.
Save up to 15% more on quarterly, half-yearly and yearly plans
Related articles

Turnstile Token Missing, Rejected or Expired: Fixes
Fix Turnstile token errors on your own forms: missing-input-response, invalid-input-response, timeout-or-duplicate, the 300-second rule and test keys.

Claude Code Web Fetch 403: Why Agents Get Blocked
Why Claude Code's WebFetch gets 403 errors: the Claude-User agent, Cloudflare agent policies, JS challenges and no JS execution, plus fixes that respect sites.

Cloudflare Error 1020 Access Denied: Scraper Fixes
Cloudflare error 1020 means a site's security rule blocked you, not a rate limit. Tell it apart from 'Sorry, you have been blocked', 1010 and 1015, and fix it.
