How to Find Frames in Selenium | Find Number of Frames
There might come a time when you are required to deal with frames on a webpage. How to find frames in Selenium? One easy way to identify a frame is using its source code.
Let’s take an example of my website: Dumb It Dude
If you navigate to the above website, you will realize it is hard to recognize a frame by just looking at it. Everything seems normal. Even a dialog box if it pops open it is not necessarily a frame. Now if you have been working with Selenium for a while, you already know that a frame if encountered has to be switched to. Your Selenium scripts are not going to identify the Xpath of the frame, as it fails to recognize its existence unless we switch to it.
Hence, I have made a short tutorial on how to deal with frames when you encounter them.
Steps on Finding Frames in a Webpage
If you are on a webpage and you want to check whether it is a frame or not, follow these simple steps: ( I will show you an example on my very site)
Step 1: Right click on the page. Then click on Inspect.
You can alternatively press Ctrl + Shift + I or F12 as a shortcut.
Step 2: Press Ctrl + F to open the search bar for elements.
Step 3: Type the following:
//iframe
Like this:
It will search all the iframes on the webpage. That number on the right side of the search bar (1 of 9) is what indicates how many iframes are there on the webpage.
So basically there are 9 frames on the page, and we are on the 1st one. Keep pressing Enter and you can easily navigate to all of them one by one.
How to Find Number of Frames in Selenium
What if you are working on Selenium, how would you find the number of frames you have in a single go?
Simply type:
driver.findElements(By.tagName("iframe")).size();
I will assign it to a variable and then sysout to see results:
int numberOfFrames = driver.findElements(By.tagName("iframe")).size(); System.out.println("no. of iframes are " + size);
If you run the above code you will get:
no. of iframes are 9
which are the same number of iFrames we saw using the Inspect Element method earlier.
Ain’t that sweet!
Now that we have known how to identify number of frames in a webpage using selenium, it is time to move on to how can we handle these frames.
Hi,
In the below example you need to call the variable name instead of method name (size) right?.
int numberOfFrames = driver.findElements(By.tagName(“iframe”)).size();
System.out.println(“no. of iframes are ” + numberOfFrames);