Selenium WebDriver : How to handle frame in webpage using selenium automation.

/*
 * @author : P programs
 * Selenium WebDriver : How to handle frame in webpage using selenium automation. 
 *
 */

An iframe is nothing but a webpage within a webpage.
Multiple iframe can be present in a webpage . To work or extract data from frame is not straight forward.We can't directly access iframe using code i.e we need to switch to frame before extracting any data or perform any operation.
We can use driver.switchTo().frame("pass_frame_index or frame_name") function to jump to particular frame in webpage.
Here is a self explanatory example in Selenium web driver.



import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;


public class FrameHandlingInSelenium {

 public static void main(String[] args) {

  
  WebDriver driver = new FirefoxDriver();
  driver.get("http://www.w3schools.com/html/tryit.asp?filename=tryhtml_iframe_height_width");
  
// First of all we need to get the list of frames present in page. we can use iframe tagname as a locator. 
  List<WebElement> pageframeList =driver.findElements(By.tagName("iframe"));

// For debugging purpose , print the size of available frames.  
  System.out.println("Total list of frames ina page. size = " + pageframeList.size()); 

// Once you identified the desired frame where you want to retrieve data, switch to that frame   
  driver.switchTo().frame("iframeResult");

// In this example, we are again going to inner frame to retrieve data.
// Get the list of all frames inside the outer frame.  
  List<WebElement> frameIn =driver.findElements(By.tagName("iframe"));
  System.out.println("Inner frame size :-" +frameIn.size());

// Either you can switch to frame using frame name or frame index.Since in this example only one frame is present
// inside.so we are directly switching using index 0.   
  driver.switchTo().frame(0);

// Now print the text inside the frame 0 using valid xpath.  
  System.out.println(driver.findElement(By.xpath("html/body/h1")).getText());
  
  driver.quit();  
 }

}

No comments:

Post a Comment

πŸ””Announcement : Visit the new website/blog πŸ””

πŸ””πŸ””πŸ”” Announcement :  Visit the new website/blog πŸ””πŸ””πŸ”” Dear readers, Thank you for reading my blog. If you could have used the little info...