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
from selenium.common.exceptions import NoSuchFrameException, TimeoutException
def test_nested_iframes():
driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)
try:
driver.get('https://example.com/nested-iframes')
# Wait and switch to outer iFrame by ID
wait.until(EC.frame_to_be_available_and_switch_to_it((By.ID, 'outer-frame')))
# Wait and switch to inner iFrame by NAME
wait.until(EC.frame_to_be_available_and_switch_to_it((By.NAME, 'inner-frame')))
# Wait for the paragraph element inside inner iFrame
paragraph = wait.until(EC.visibility_of_element_located((By.ID, 'inner-text')))
# Assert the paragraph text
assert paragraph.text == 'Hello from nested iFrame!', f"Expected text not found, got: {paragraph.text}"
except (NoSuchFrameException, TimeoutException) as e:
assert False, f"Test failed due to missing frame or element: {e}"
finally:
# Always switch back to default content
driver.switch_to.default_content()
driver.quit()
if __name__ == '__main__':
test_nested_iframes()This test script opens the target web page with nested iFrames.
It uses explicit waits to ensure the outer iFrame is available, then switches to it by its ID 'outer-frame'.
Next, it waits for the inner iFrame by its name 'inner-frame' and switches to it.
Inside the inner iFrame, it waits for the paragraph element with ID 'inner-text' to be visible.
It asserts that the paragraph text exactly matches 'Hello from nested iFrame!'.
If any frame or element is missing, it catches exceptions and fails the test with a clear message.
Finally, it switches back to the main page content and closes the browser to clean up.