Introduction
While automating web applications, handling iFrames is a common challenge we have faced. An iframe, also known as inline Frame, is an HTML element that helps to embed another document within the desired page. Selenium interacts with the primary DOM by default, so we need to explicitly switch to the iframes before interacting with any iframe elements. Today, in this article, we will see how we can efficiently handle iframes in selenium ruby.
Prerequisites
- Installed Ruby on you computer system
- Installed Selenium WebDriver Gem
- And web browser drivers like geckodriver, chromedriver.
What is iFrames?
An iframe is a separate embedded document within a webpage. An iframe has its own DOM, different from the main web page. Since selenium cannot interact directly inside of an iframe element unless we switch the context to it first.
Now let’s discuss how we can work with different iframes easily on selenium ruby.
Steps to Handle iFrames in Selenium Ruby
Identify required Iframe
To work on any elements inside an iframe, we first have to locate them using different element locators such as CSS locator, xpath, name, id
Switch to the Iframe
Selenium provides its method, the switch_to.frame
method, for switching between iframes.
driver.switch_to.frame(id: 'your_iframe_id')
Use replace id: 'your_iframe_id'
with your locator
Performing Action within the Iframe
Once you switch to a new iframe, you can easily interact with the elements like you normally would, such as filling input text fields, clicking buttons, etc.
element = driver.find_element(:css, 'input[id="text"]')
element.send_keys('How to Handle iFrames in Selenium Ruby')
Switch back to the mainframe
After completing the task within the iframe, we may need to switch back to the main content to continue further actions in the web application. To switch back to the Main Content frame we use default_content
method in selenium ruby.
driver.switch_to.default_content
Summary
Handling iframes in Selenium with Ruby requires proper context switching to interact with elements inside iframes. Using appropriate switch methods and handling exceptions such as StaleElementReferenceError, NoSuchFrameError, ElementNotInteractableError, etc., will ensure a smooth automation testing experience. With best practices, we can create robust and reliable selenium scripts for automation testing.
After all, Quality Matters!!!! Cheers!!!