Use iframe with selenium

selenium

To switch iframe we can use this sample code –

package com.webdriver_07;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.ErrorHandler.UnknownServerException;

public class MyIframe {

	public WebDriver driver;
	private String baseUrl;
	
	public static void main(String[] args){
		MyIframe mif = new MyIframe();
		mif.launch_browser();
	}
	public void launch_browser() {
		try{
		baseUrl = "http://demo.tanmaysarkar.com/sample_02.html";		
		driver = new FirefoxDriver();
		driver.get(baseUrl);
		driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
		
		List<WebElement> frms= driver.findElements(By.tagName("iframe"));  
		System.out.println(frms.size());
		for(int i=0;i<frms.size();i++)
		{
			System.out.println(frms.get(i).getAttribute("src"));
		}
			
		 WebElement ifr = driver.findElement(By.xpath("//iframe[@src='frame_02.html']"));
		 driver.switchTo().frame(ifr);
		 driver.findElement(By.id("ts_first_name")).sendKeys("tanmay");
		 driver.findElement(By.id("ts_last_name")).sendKeys("sarkar");
		 driver.switchTo().defaultContent();
		 driver.findElement(By.id("ts_in_main")).sendKeys("welcome back");
		}
		catch(NoSuchElementException ne)
		{
			System.out.println(ne.getLocalizedMessage());
		}
		catch(UnknownServerException u)
		{
			System.out.println(u.getLocalizedMessage());
		}
	}
}

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *