How to Handle Multiple Frames in Selenium WebDriver
Here is the example of multiple frames in a web page and how to interact with them.
There is three overloaded frame () methods, to switch to the frame.

How to decide when to use which method???
If it’s a static web page and so frame elements are, then zero-based index [frame(int index)] locating strategy can be used to locate the frame.
If the frame element is having unique name or id attribute, then frame could be located with its name or id attribute. [frame(java.lang.StringnameOrId)]
If frame is not located either with above mechanism, then it can be located with it’s web element. [frame (WebElementframeElement)]
Here is an example:-
0 based index is used here.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
import java.util.concurrent.TimeUnit;
importorg.openqa.selenium.By;
importorg.openqa.selenium.WebDriver;
importorg.openqa.selenium.firefox.FirefoxDriver;
public class RecaptchaExample {
public static void main(String[] args) {
WebDriver d = new FirefoxDriver();
d.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
d.manage().window().maximize();
d.get(“https: //www.google.com/recaptcha/api2/demo“);
d.switchTo().frame(0);
d.findElement(By.id(“recaptcha - anchor”)).click();
d.switchTo().defaultContent();
d.switchTo().frame(1);
System.out.println(d.findElements(By.tagName(“iframe”)).size());
d.findElement(By.xpath(“ //*[text()=’Verify’]”)).click();
}
}
|
After working with the frame, main important is to come back to the web page. if we don’t switch back to the default page, driver will throw an exception. You’ll have to use defaultContent() method.
|
1
|
driver.switchTo().defaultContent();
|



Hey Rahul,
Thanks for the great article. This really helped me in solving frame handling issue I had while automating our enterprise application.
Thanks,
Hussain
Nice post thank you for sharing.