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:
- Selenium Features
- Selenium Installation
- Selenium Locators
- XPath Fundamentals
- CSS Selectors Methods
- Different Browsers Execution
- find_element & find_elements
- Check Enabled Status
- Check Displayed Status
- Check Selected Status
- Selenium Waits
- Send_keys Method
- Click Method
- Get Text
- Get Attribute Value
- Get Current URL
- Forward, Back, Refresh
- Take Screenshot
- Handle Browser Tabs
- Handle iframe
- Mouse Hover
- Context-Click
- Drag & Drop
- Handle Alerts
- Handle Dropdown
- Execute Javascript
- Scroll To element
- Headless Mode Execution
- Chrome Options
- Keyboard Action
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
orid
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.