FRAMES & IFRAMES AUTOMATION IN PYTHON

Master seamless nested document automation in Playwright with Python: frame_locator, frame switching elimination, deeply nested iframes, cross-origin security boundaries, frame objects, and auto-waiting inside embedded views.

πŸ–ΌοΈ The Playwright FrameLocator Revolution

In traditional test automation tools like Selenium WebDriver, automating embedded <iframe> elements is notoriously brittle: test code must explicitly switch driver focus into a frame (driver.switch_to.frame()), interact with elements, and remember to switch back to the main document (driver.switch_to.default_content()). If an element is re-rendered or an unexpected exception occurs, the test runner gets stranded inside the wrong frame context. Playwright revolutionizes iframe automation using FrameLocator objects. Frame locators are composable, auto-waiting, thread-safe references that allow targeting elements inside any frameβ€”or multiple levels of nested framesβ€”without ever mutating the global page context.

1. Selenium Context Switching vs. Playwright FrameLocators
Selenium relies on a stateful driver pointer that must be moved in and out of frames manually. Playwright uses stateless, lazy FrameLocators that automatically focus on the target frame during action execution.
Execution Paradigm Comparison
LEGACY SELENIUM WORKFLOW (Stateful & Fragile):
[ Main Page ] ──► driver.switch_to.frame("payment-gate")
                          β”‚
                          β–Ό (Driver Context Locked Inside Iframe)
                  driver.find_element(By.ID, "card-num").send_keys("4242")
                          β”‚
                          β–Ό (Must Manually Reset Context)
                  driver.switch_to.default_content()
                  driver.find_element(By.ID, "submit-order").click()

PLAYWRIGHT COMPOSABLE FRAMELOCATOR (Stateless & Direct):
# Target inside iframe directly without switching global context:
page.frame_locator("#payment-gate").locator("#card-num").fill("4242")

# Immediately interact with main document in the very next line:
page.locator("#submit-order").click()
Architectural Advantage: Zero context-switching overhead. Iframes and parent pages can be interacted with simultaneously in parallel without state collisions.
Real-Time Example 1: Basic iFrame Interaction via frame_locator()
Locate an iframe using any standard CSS or XPath selector, obtain a FrameLocator, and interact with child form inputs, buttons, and text labels inside the embedded document.
Python (frame_locator Basic Usage)
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    # Host page containing an embedded iframe
    page.set_content("""
        

Parent Host Application

""") # 1. Create a FrameLocator reference pointing to the iframe element frame = page.frame_locator("#newsletter-frame") # 2. Scope locators inside the frame and interact email_field = frame.get_by_placeholder("Enter corporate email") subscribe_btn = frame.locator("#sub-btn") success_msg = frame.locator("#msg") email_field.fill("qa-lead@nikita-infotech.com") subscribe_btn.click() # 3. Web-first auto-waiting assertion inside the iframe expect(success_msg).to_be_visible() expect(success_msg).to_have_text("Subscription Confirmed!") print(f"Verified iFrame Action Result: '{success_msg.inner_text()}'") browser.close()
Output: Verified iFrame Action Result: 'Subscription Confirmed!'
Real-Time Example 2: Deeply Nested iFrames (Frame within a Frame)
Enterprise portals and third-party authentication gateways frequently nest iframes two or three levels deep. Chain frame_locator() calls sequentially to drill down effortlessly.
Python (Nested Frame Chaining)
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    # Two levels of nested iframes
    page.set_content("""
        

Main Application Root

""") # Chain outer frame locator into inner frame locator cleanly nested_frame = page.frame_locator("#outer-frame").frame_locator("#inner-frame") token_display = nested_frame.locator("#nested-content") confirm_btn = nested_frame.locator("#confirm-token") # Assertions and actions inside the deeply nested document expect(token_display).to_contain_text("99482") expect(confirm_btn).to_be_enabled() confirm_btn.click() print(f"Deeply Nested Element Located: '{token_display.inner_text()}'") browser.close()
Output: Deeply Nested Element Located: 'Secret Security Verification Token: 99482'
Real-Time Example 3: Locating Frames by Name or URL via page.frame()
Beyond CSS-based FrameLocators, Playwright exposes page.frame() to look up concrete Frame objects directly by their HTML name attribute or destination URL regular expression.
Python (page.frame Name & URL Matching)
import re
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    page.set_content("""
        
    """)

    # 1. Lookup Frame object by its HTML name attribute
    frame_by_name = page.frame(name="payment-gateway-frame")
    print(f"Discovered Frame by Name: '{frame_by_name.name}'")

    # 2. Lookup Frame object by its URL regex match
    frame_by_url = page.frame(url=re.compile(r".*example\.com.*"))
    print(f"Discovered Frame by URL : '{frame_by_url.url}'")

    # Interact using the Frame instance
    heading = frame_by_url.locator("h1")
    expect(heading).to_have_text("Example Domain")

    print(f"Verified Content inside Frame Object: '{heading.inner_text()}'")
    browser.close()
Output: Discovered Frame by Name: 'payment-gateway-frame' Discovered Frame by URL : 'https://example.com/' Verified Content inside Frame Object: 'Example Domain'
Real-Time Example 4: Iterating Across All Page Frames via page.frames
Inspect the entire frame tree across third-party analytics embeds, ad tags, and utility widgets using the page.frames collection and page.main_frame.
Python (Frame Hierarchy Inspection)
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    page.set_content("""
        

Dashboard Container

""") # Retrieve all frames currently attached to the page all_frames = page.frames print(f"Total Attached Frames Count: {len(all_frames)} (1 Main Frame + 3 Child Frames)") for idx, f in enumerate(all_frames): is_root = (f == page.main_frame) label = "MAIN ROOT FRAME" if is_root else f"CHILD IFRAME (name='{f.name}')" print(f" [{idx}] {label} -> URL: {f.url}") browser.close()
Output: Total Attached Frames Count: 4 (1 Main Frame + 3 Child Frames) [0] MAIN ROOT FRAME -> URL: about:blank [1] CHILD IFRAME (name='widget-stocks') -> URL: about:srcdoc [2] CHILD IFRAME (name='widget-weather') -> URL: about:srcdoc [3] CHILD IFRAME (name='widget-news') -> URL: about:srcdoc
Real-Time Example 5: Cross-Origin iFrames & Payment Gateway Fields
Automating secure credit card gateways (Stripe, Razorpay, PayPal) where input fields live in isolated third-party cross-origin domains. Playwright pierces cross-origin boundaries natively.
Python (Cross-Origin Payment Gateway Pattern)
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    # Mock checkout page embedding a secure card iframe
    page.set_content("""
        

Order Total: β‚Ή 8,500

""") # 1. Fill cardholder name on the parent document page.locator("#holder-name").fill("Pooja Patil") # 2. FrameLocator directly targets inputs inside the secure payment iframe card_frame = page.frame_locator("#secure-card-frame") card_frame.locator("#card-number").fill("4111 2222 3333 4444") card_frame.locator("#card-expiry").fill("12/28") card_frame.locator("#card-cvv").fill("921") # 3. Immediately interact with the parent checkout button without switching back! pay_btn = page.locator("#pay-now-btn") expect(pay_btn).to_be_enabled() pay_btn.click() print("Cross-origin payment iframe form populated without any driver switching!") browser.close()
Output: Cross-origin payment iframe form populated without any driver switching!
Real-Time Example 6: Listening to Frame Lifecycle Events (frameattached, framenavigated)
Single Page Applications often inject or destroy iframes dynamically. Monitor the frame lifecycle in real-time by hooking listeners to frameattached, framenavigated, and framedetached.
Python (Frame Lifecycle Event Listeners)
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    lifecycle_events = []

    # Register frame lifecycle listeners
    page.on("frameattached", lambda f: lifecycle_events.append(f"ATTACHED: {f.name or 'unnamed'}"))
    page.on("framenavigated", lambda f: lifecycle_events.append(f"NAVIGATED: {f.url}"))
    page.on("framedetached", lambda f: lifecycle_events.append(f"DETACHED: {f.name or 'unnamed'}"))

    # Dynamically inject an iframe into the DOM using JavaScript
    page.set_content("

Host Page

") page.evaluate("""() => { const frame = document.createElement('iframe'); frame.name = 'dynamic-auth-frame'; frame.src = 'about:blank'; document.body.appendChild(frame); }""") # Remove the iframe dynamically page.evaluate("() => document.querySelector('iframe').remove()") print("Captured Frame Lifecycle Events Stream:") for event in lifecycle_events: print(" ", event) browser.close()
Output: Captured Frame Lifecycle Events Stream: ATTACHED: dynamic-auth-frame NAVIGATED: about:blank DETACHED: dynamic-auth-frame
Real-Time Example 7: Executing JavaScript inside Frame Context via evaluate()
Run custom client-side JavaScript expressions or query window / document objects strictly inside the isolated context of an embedded frame using frame.evaluate().
Python (frame.evaluate Execution)
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    page.set_content("""
        

Host Document

""") # Obtain Frame object via name/URL frame_obj = page.frame(url=re.compile(r".*srcdoc.*")) if 're' in locals() else page.frames[1] # Evaluate JavaScript strictly inside the iframe global window scope session_id = frame_obj.evaluate("() => window.FRAME_SESSION_ID") frame_title = frame_obj.evaluate("() => document.body.innerText.trim()") print(f"Evaluated JS inside Frame Window Scope:") print(f" window.FRAME_SESSION_ID : '{session_id}'") print(f" Frame Body Content : '{frame_title}'") browser.close()
Output: Evaluated JS inside Frame Window Scope: window.FRAME_SESSION_ID : 'AUTH_SESS_88319' Frame Body Content : 'Analytics Engine Active'
Real-Time Example 8: Page Object Model (POM) Design with FrameLocators
Encapsulate iframe components inside dedicated Page Object Model sub-classes by storing the FrameLocator as the root attribute, completely hiding iframe complexity from test scripts.
Python (POM FrameLocator Architecture)
from playwright.sync_api import Page, FrameLocator, sync_playwright, expect

class EmbeddedPaymentWidget:
    """Component Object Model encapsulating an embedded billing iframe."""

    def __init__(self, frame_root: FrameLocator):
        self.frame = frame_root
        self.card_input = self.frame.locator("#card-num")
        self.cvv_input = self.frame.locator("#card-cvv")
        self.submit_btn = self.frame.locator("#submit-pay")
        self.status_msg = self.frame.locator("#pay-status")

    def submit_payment(self, card_number: str, cvv: str):
        self.card_input.fill(card_number)
        self.cvv_input.fill(cvv)
        self.submit_btn.click()

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    page.set_content("""
        

Checkout Portal

""") # Instantiate component with FrameLocator root payment_widget = EmbeddedPaymentWidget(page.frame_locator("#payment-embed")) payment_widget.submit_payment("4242 4242 4242 4242", "123") expect(payment_widget.status_msg).to_be_visible() print("Page Object Model iframe component executed seamlessly!") browser.close()
Output: Page Object Model iframe component executed seamlessly!
Real-Time Example 9: FrameLocator vs. Frame Object Reference Matrix
A comprehensive reference summary comparing the capabilities, lifecycle handling, and primary use cases of FrameLocator versus Frame objects in Playwright Python.
Frame API Comparison Matrix
PLAYWRIGHT FRAMES API COMPARISON MATRIX:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Capability / Dimension       β”‚ FrameLocator           β”‚ Frame Object           β”‚
β”‚                              β”‚ (page.frame_locator)   β”‚ (page.frame, .frames)  β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Construction Syntax          β”‚ CSS or XPath Selector  β”‚ name: str / url: Regex β”‚
β”‚ Auto-Waiting on Elements     β”‚ βœ“ Yes (Full auto-wait) β”‚ βœ— Limited manual checksβ”‚
β”‚ Re-rendering Resilience      β”‚ βœ“ Seamless (Retries)   β”‚ βœ— Stale if frame reloadβ”‚
β”‚ Chaining / Deep Nesting      β”‚ βœ“ Composable chaining  β”‚ Requires manual child()β”‚
β”‚ Cross-Origin Support         β”‚ βœ“ Full native support  β”‚ βœ“ Full native support  β”‚
β”‚ JavaScript Execution         β”‚ Via child locators     β”‚ βœ“ Direct frame.evaluateβ”‚
β”‚ Lifecycle Event Hooks        β”‚ N/A (Locator handle)   β”‚ βœ“ on("load"), etc.     β”‚
β”‚ Recommended Primary Use      β”‚ β˜… All UI Test Actions  β”‚ Frame Diagnostics,     β”‚
β”‚                              β”‚ (Clicks, Inputs, expectβ”‚ URL checks, Scraping   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Engineering Best Practice: Always prefer page.frame_locator() for UI testing actions and assertions; reserve page.frame() and page.frames for low-level frame tree diagnostics and JavaScript evaluations.