How to handle frame in selenium WebDriver?
In this article, i will talk about how to handle frame in selenium webdriver.
What is frame?
Frame is nothing but a container where few elements are grouped together. In short Frame is a HTML document within HTML document (Page). In HTML frames are also called as Iframe (Inline Frame). On HTML pages, iframes are mostly used to add content from another source (page), like advertisement.
How to Identify if frame is present on WebPage?
Below Image shows you how to identify frame.
On my blog : https://automationtalks.com/ My name card of LinkedIn appear as frame. refer below screenshot
As we saw earlier, the frame will have tagName “iFrame”. So we can use this tagname to find out number of frames present on the WebPage.
Get the number of frames in the list.
List<WebElement> frameList=driver.findElements(By.tagName(“iframe”)); System.out.println(“Total number of frames present: ”+frameList.size());
In order to deal with the elements present on the frame, first we need to switch to that respective frame. Let us see how this can be done
Scenario 1: If we know the number of frames present on the page-
If you know about number of frames present on the webpage, and you are sure about the frame number to which you wanted to switch, we can use index number (frame number) to switch to frame.
WebDriver driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.manage().window().maximize(); driver.navigate().to("https://learnaboutsoftwaretesting.blogspot.in"); try { driver.switchTo().frame(indexnumber); //here you can enter the index number } catch (NoSuchFrameException e) { System.out.println(e.getMessage()); }
Scenario 2: if you know the frame name.
If you know the frame name, How to handle frame, we can use –
WebDriver driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.manage().window().maximize(); driver.navigate().to("https://learnaboutsoftwaretesting.blogspot.in"); try { driver.switchTo().frame("frameName"); //enter the frame name here } catch (NoSuchFrameException e) { System.out.println(e.getMessage()); }
Scenario 3: if you don’t know about number of frames and frame names.
WebDriver driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.manage().window().maximize(); driver.navigate().to("https://learnaboutsoftwaretesting.blogspot.in"); try { WebElement button=driver.findElement(By.xpath("")); driver.switchTo().frame(button); } catch (NoSuchFrameException e) { System.out.println(e.getMessage()); }
driver.switchTo().defaultContent();