DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Selenium Grid Tutorial: Essential Tips and How to Set It Up
  • Spice Up Your 'CI/CD Process' With Automation Using Cucumber, Selenium, and Kotlin
  • Selenium Test Automation— Critical Things to Avoid When Writing Test Scripts
  • Playwright: Test Automation You Must Know

Trending

  • Designing a Java Connector for Software Integrations
  • Mastering Advanced Aggregations in Spark SQL
  • Developers Beware: Slopsquatting and Vibe Coding Can Increase Risk of AI-Powered Attacks
  • Unlocking AI Coding Assistants: Generate Unit Tests
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Handling Iframes in Selenium Based Test Automation

Handling Iframes in Selenium Based Test Automation

An iFrame is commonly known as an inline frame which is nothing but an HTML document embedded inside another HTML document. iFrames are a simpler way to embed a web page inside another web page.

By 
Ramit Dhamija user avatar
Ramit Dhamija
·
Apr. 26, 22 · Analysis
Likes (2)
Comment
Save
Tweet
Share
3.5K Views

Join the DZone community and get the full member experience.

Join For Free

An iFrame is commonly known as an inline frame which is nothing but an HTML document embedded inside another HTML document. iFrames are a simpler way to embed a web page inside another web page. iFrames are mostly used to display external information on the webpage like displaying advertisements and videos from third-party sources.

The iFrame is basically a tag used in HTML5 like <iframe></iframe>.

As a point to highlight, there’s a difference between iFrame and Frame in Selenium. While the iFrames are used to embed content from external sources, the frames leverage developers to split the web page vertically or horizontally with the frameset tags.

How To Identify Iframes on a Web Page?

Looking at the web page and identifying the iframes is definitely not possible. So the question is, how to identify whether an element is on an iframe or not? You just have to right-click on the suspected element and check whether you are getting an option such as: ‘This Frame’, ‘View Frame Source’, or ‘Reload Frame’. After right-clicking on an element, if you get an option related to frames, that simply means, the element you are trying to locate is aligned on an iframe.

There might be a possibility that a parent web page embeds multiple iframes. In such a case, you can open the browser dev tools and checkout the required iframe by searching the keyword ‘iframe’ under the ‘Elements’ tab of dev tools. With Selenium-based test automation, you can also get the count of iframes on a particular web page with the below code snippet :

Java
 
int iFrameSize = driver.findElements(By.tagName("iframe")).size();

How to Switch Selenium Webdriver to Elements Over Iframe?

To switch over the elements and handle the web iframes in selenium, the Selenium framework offers 3 common ways:

  • Switch To iFrame By Index: Switching to iframe using the index is probably used when there are multiple iframes present on a single web page. The index of iframe starts with 0 and the index gets increasing with the number of iframes embedded. If there are 2 iframes present on a web page, you can use the below code snippet to switch to iframes in Selenium :
Java
 
driver.switchTo().frame(0);
driver.switchTo().frame(1);
  • Switch To iFrame By Name or ID: The name and ID attribute is the most common way of switching to an iframe using Selenium. You can easily fetch either the name or ID of the iframe from the browser dev tools.

To locate the targeted element over iframe using name or id, the below code snippet can be used :

Java
 
driver.switchTo().frame("iFrameID");
OR
driver.switchTo().frame("iFrameName");
  • Switch To iFrame By Web Element: Another way of switching to iframe using Selenium is to use the Web Element in the switchTo() command. Here the idea is to get the iframe element from browser dev tools and pass it to the switch method. To locate the targeted element over an iframe using a web element, the below code snippet can be used :
Java
 
WebElement iframeElement = driver.findElement(By.id("webElementID"));    
driver.switchTo().frame(iframeElement);

How to Switch the Selenium Webdriver Back to the Main Frame?

Not all elements of the web page are aligned on an iframe. As discussed earlier, iframes are majorly used to display external applications, videos, or advertisements. As a part of Web test automation, you may find a scenario where all the major operations are being performed on a parent web page, but to just click on another specific element you have to switch to the targeted frame and switch back to the parent frame so that the web driver can continue its operation on the main webpage.

To switch back the Selenium Webdriver to the mainframe, Selenium offers two in-built methods:

  1. parentFrame()
  2. defaultContent()

Code snippet :

Java
 
driver.switchTo().parentFrame();
driver.switchTo().defaultContent();

Switching Over the Iframe When Iframe ID, Name, and Web Element Doesn’t Work or Isn’t Present

The common questioned scenario: how to handle iframes in Selenium when iframe ID, Name, and Web Element don’t work or aren’t present?

Let’s imagine that there are 100 iframes embedded on a single web page and there is no iframe id or name available. In the case of 100 iframes, suspecting the index of the iframe is also a complex task. Hence, we have to adopt some strategy that could identify the iframe of the targeted element.

As a resolution to the above scenario, it is important to fetch the index of the iframe on which the targeted element is being loaded, and then we can switch to the iframe using its index. Let’s have a look at the below script and code walkthrough to automate such scenarios.

Java
 
public class SeleniumIframe {
public static void main(String[] args) {
 
    WebDriver driver = new ChromeDriver();
    driver.get("URL"); 
    driver.manage().window().maximize();
Java
 
int iFrameSize = driver.findElements(By.tagName("iframe")).size();
Java
 
for(int i=0; i<=iFrameSize; i++){
  driver.switchTo().frame(i);
  int elementSize = driver.findElements(By.xpath("html/body/a/advertVideo")).size();
  System.out.println(elementSize);
    driver.switchTo().defaultContent();
  }
  }
}

Code Walkthrough :

Since there are multiple iframes embedded on a single web page, we have used a tagName Selenium locator to get the total number of iframes present. Once we are aware of the actual iframe count, we have to start a loop till the size of the iframe. And in a running loop, we are switching to each iframe present on the web page and fetching the size of the targeted element. Whenever the loop gets executed for the correct iframe, we would get the element size as 1 else size of the web element would remain 0.

This way, we could extract the index of the iframe. Once we get the exact index the iframe, we can then comment on the loop to avoid running against every iframe embedded on the web page.

Handling Nested Iframes in Selenium Test Automation

Let’s assume that the targeted element is on an iframe aligned with another iframe, this kind of structure is known as nested iframes.

In selenium test automation, we first have to interact with the iframe1, then with the iframe 2 to perform the operation on the targeted web element. Below is the HTML structure of the nested iframe where the second iframe tag is embedded in the first iframe tag.

HTML
 
<div class="iframe">
<div style="overclow:auto;">
  <div id="iframewrapper" class="iframewrapper">
<iframe id="iframeResult" frameborder="0">
<html>
  <head>
  <body>
<iframe width="200" height="200" src="demo_iframe.htm">
</body>
</head>
</html>

In the test automation scenario of nested iframes, the mandate steps that need to be followed are:

  • Firstly, we need to switch to the outer frame, either by name, ID, or index
  • After switching to the outer iframe, we can fetch the count of inner iframes in selenium
  • We can then switch to the inner frame with any of the available types i.e ID, name, or index
  • Lastly, we can interact with the targeted element.

Conclusion

Understanding how iframes work will help in accurately targeting the right web elements we want to test using Selenium automation. We have discussed various ways by which we can use iframes in the selenium test automation.

Test automation Element IFrame (video format) Testing Selenium

Published at DZone with permission of Ramit Dhamija. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Selenium Grid Tutorial: Essential Tips and How to Set It Up
  • Spice Up Your 'CI/CD Process' With Automation Using Cucumber, Selenium, and Kotlin
  • Selenium Test Automation— Critical Things to Avoid When Writing Test Scripts
  • Playwright: Test Automation You Must Know

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!