Handle Iframes In Selenium

To handle iframes in Selenium using Python, you need to switch the WebDriver’s context to the iframe first using the switch_to.frame() method. Here is a basic guide on working with iframes:

Example Code

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

# launch Chrome browser
driver = webdriver.Chrome()

# navigate to a page with an iframe
driver.get("https://www.globalsqa.com/demo-site/frames-and-windows/#iFrame")

# get iframe web element
iframe_element = driver.find_element(By.XPATH, "//iframe[@name='globalSqa']")

# switch to iframe with web element
driver.switch_to.frame(iframe_element)

# get web element of header email inside iframe
header_email = driver.find_element(By.XPATH, "//div[@class='header_mail']")

# get email from web page with text
print(header_email.text)

# switch default main page
driver.switch_to.default_content()

# get Tester web element from default content
tester_hub_elem = driver.find_element(By.XPATH, "//div[@id='menu']//a[contains(text(),'Tester')]")

# click on menu option
tester_hub_elem.click()

time.sleep(5)
driver.close()

Explanation:

  • driver.switch_to.frame(“frame_name_or_id”): Switches to an iframe using its name or id attribute.
  • driver.switch_to.frame(index): Switches to an iframe using its index (0-based).
  • driver.switch_to.frame(iframe_element): Switches using a WebElement representing the iframe.
  • driver.switch_to.default_content(): Switches back to the main document from an iframe.

This approach allows you to interact with elements inside the iframe and switch between the main content and other frames when necessary.