How to count the number of frames in a page in Selenium?



We can count the number of frames in Selenium by the methods listed below −

  • With the help of List<WebElement> with tagname frame/iframe.

  • With the help of a Javascript executor.

Example

With tagname.

import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import java.util.List; public class FrameCount{    public static void main(String[] args) {       System.setProperty("webdriver.chrome.driver",       "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");       WebDriver driver = new ChromeDriver();       String url =       "http://the-internet.herokuapp.com/nested_frames";       driver.get(url);       driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);       //By finding list of the web elements using frame or iframe tag       List<WebElement> f = driver.findElements(By.tagName("frame"));       System.out.println("Total number " + f.size());       driver.quit();    } }

Example

With Javascript Executor.

import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.Keys; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.JavascriptExecutor; import java.util.concurrent.TimeUnit; public class FrameCountJS{    public static void main(String[] args) {       System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");       WebDriver driver = new ChromeDriver();       String url = "http://the-internet.herokuapp.com/nested_frames";       driver.get(url);       driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);       //Javascript executor script to get the window length       JavascriptExecutor exe = (JavascriptExecutor) driver;       int f = Integer.parseInt(exe.executeScript("return window.length").toString());       System.out.println("No. of iframes on the page are " + f);       driver.quit();    } }
Updated on: 2020-06-10T15:02:33+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements