from pathlib import Path from tempfile import TemporaryDirectory import os import shutil from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait FRAME_HTML = """ Checkout frame

Waiting for iframe action

""" PARENT_HTML = """ Selenium iframe switch demo

Checkout wrapper

Parent document restored

""" options = Options() options.add_argument("--headless=new") options.add_argument("--disable-dev-shm-usage") options.add_argument("--window-size=1280,720") if hasattr(os, "geteuid") and os.geteuid() == 0: options.add_argument("--no-sandbox") for browser_name in ("google-chrome", "chromium", "chromium-browser"): browser_path = shutil.which(browser_name) if browser_path: options.binary_location = browser_path break driver_path = shutil.which("chromedriver") service = Service(driver_path) if driver_path else Service() with TemporaryDirectory() as tmpdir: frame_page = Path(tmpdir) / "checkout-frame.html" parent_page = Path(tmpdir) / "checkout.html" frame_page.write_text(FRAME_HTML, encoding="utf-8") parent_page.write_text( PARENT_HTML.format(frame_uri=frame_page.as_uri()), encoding="utf-8", ) driver = webdriver.Chrome(service=service, options=options) try: driver.get(parent_page.as_uri()) wait = WebDriverWait(driver, 10) wait.until( EC.frame_to_be_available_and_switch_to_it( (By.CSS_SELECTOR, "iframe#checkout-frame") ) ) wait.until(EC.visibility_of_element_located((By.ID, "customer-email"))).send_keys( "qa@example.net" ) driver.find_element(By.ID, "confirm-payment").click() frame_status = wait.until( EC.text_to_be_present_in_element( (By.ID, "frame-status"), "Ready for qa@example.net", ) ) status_text = driver.find_element(By.ID, "frame-status").text driver.switch_to.default_content() parent_status = driver.find_element(By.ID, "parent-status").text print(f"title: {driver.title}") print(f"frame_switched: {frame_status}") print(f"frame_status: {status_text}") print(f"parent_status: {parent_status}") finally: driver.quit()