Course → 1 · Selenium automation → Alerts, Frames & Windows
1 · Selenium automation
Windows and iframes
12 min · Module 12
Use driver.window_handles to switch tabs/windows. Use driver.switch_to.frame(...) for iframes, then switch_to.default_content() to leave.
Example / notes
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("http://127.0.0.1:8000/lab/windows/")
main = driver.current_window_handle
driver.find_element(By.ID, "open-window").click()
for handle in driver.window_handles:
if handle != main:
driver.switch_to.window(handle)
break
assert "iframe-heading" in driver.page_source or driver.find_element(By.ID, "iframe-heading")
driver.close()
driver.switch_to.window(main)
driver.switch_to.frame("lab-iframe")
driver.find_element(By.ID, "iframe-button").click()
assert driver.find_element(By.ID, "iframe-clicked").is_displayed()
driver.switch_to.default_content()
driver.quit()
Practice in Lab: /lab/windows/
Modules in this track
- 6. Getting Started
- 7. Finding Elements
- 8. Interactions
- 9. Waits
- 10. Assertions & Structure
- 11. Page Object Model
- 12. Alerts, Frames & Windows
- 13. Headless & Next Steps