An iframe (inline frame) is used to embed another HTML document within the current one. To interact with elements inside an iframe, you must first switch the WebDriver’s context to the iframe. You can do this in three ways:
- By Index:
driver.switchTo().frame(index)
(e.g.,driver.switchTo().frame(0)
). - By Name or ID:
driver.switchTo().frame("frameName")
ordriver.switchTo().frame("frameID")
. - By WebElement:
driver.switchTo().frame(driver.findElement(By.tagName("iframe")))
.
To switch back to the main page, use driver.switchTo().defaultContent()
. For nested iframes, you switch to the parent iframe first using driver.switchTo().parentFrame()
and then to the child iframe.