Working with Frames in Selenium Webdriver
What is iFrame ?
An iFrame (Inline Frame) is an HTML document embedded inside the current HTML document on a website. iFrame HTML element is used to insert content from another source, such as an advertisement, into a Web page. A Web designer can change an iFrame's content without making them reload the complete website. A website can have multiple frames on a single page. And a frame can also have inner frames (Frame in side a Frame).
In Selenium to work with iFrames, we have different ways to handle frame depending on the need. Please look at the below ways of handling frames
Select a frame by its (zero-based) index. That is, if a page has multiple frames (more than 1), the first frame would be at index "0", the second at index "1" and so on.
Once the frame is selected or navigated , all subsequent calls on the WebDriver interface are made to that frame. i.e the driver focus will be now on the frame. What ever operations we try to perform on pages will not work and throws element not found as we navigated / switched to Frame.Returns: driver focused on the given frame (current frame)
Throws: NoSuchFrameException - If the frame is not found.
public void switchToFrame(int frame) {
try {
driver.switchTo().frame(frame);
System.out.println("Navigated to frame with id " + frame);
} catch (NoSuchFrameException e) {
System.out.println("Unable to locate frame with id " + frame
+ e.getStackTrace());
} catch (Exception e) {
System.out.println("Unable to navigate to frame with id " + frame
+ e.getStackTrace());
}
}
Parameters: name Or Id - the name of the frame or the id of the frame element.
Returns: driver focused on the given frame (current frame)
Throws: NoSuchFrameException - If the frame is not found
public void switchToFrame(String frame) {
try {
driver.switchTo().frame(frame);
System.out.println("Navigated to frame with name " + frame);
} catch (NoSuchFrameException e) {
System.out.println("Unable to locate frame with id " + frame
+ e.getStackTrace());
} catch (Exception e) {
System.out.println("Unable to navigate to frame with id " + frame
+ e.getStackTrace());
}
}
Parameters: Index - (zero-based) index
Example: if iframe id=webklipper-publisher-widget-container-frame, it can be written as driver.switchTo().frame("webklipper-publisher-widget-container-frame"); Below is the code snippet to work with switchToFrame using frame id.