Web pages often use iFrames to show content from other sources. To test elements inside an iFrame, you must switch your focus to it first.
iFrame switching (switchTo.frame) in Selenium Java
driver.switchTo().frame(frameIdentifier);
frameIdentifier can be an index (int), name or ID (String), or a WebElement representing the iFrame.
Always switch back to the main page using driver.switchTo().defaultContent(); after working inside the iFrame.
driver.switchTo().frame(0);driver.switchTo().frame("frameName");WebElement iframeElement = driver.findElement(By.cssSelector("iframe.someClass"));
driver.switchTo().frame(iframeElement);This program opens a page with an iFrame, switches into the iFrame, reads a heading inside it, then switches back to the main page and prints its title.
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class IFrameSwitchExample { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://www.w3schools.com/html/html_iframe.asp"); // Switch to the iframe by CSS selector WebElement iframe = driver.findElement(By.cssSelector("iframe[src='https://www.w3schools.com']")); driver.switchTo().frame(iframe); // Find an element inside the iframe and print its text WebElement heading = driver.findElement(By.cssSelector("h1")); System.out.println("Heading inside iframe: " + heading.getText()); // Switch back to the main page driver.switchTo().defaultContent(); // Print title of main page System.out.println("Main page title: " + driver.getTitle()); } finally { driver.quit(); } } }
Always switch back to the main page after working inside an iFrame to avoid errors.
Using the WebElement to switch frames is often more reliable than using index or name.
If you try to find elements inside an iFrame without switching, Selenium will throw a NoSuchElementException.
iFrames are like windows inside a web page; you must switch focus to them to interact with their content.
Use driver.switchTo().frame() with index, name/ID, or WebElement to switch.
Always return to the main page with driver.switchTo().defaultContent() after finishing.