A web page can have any number of iframes (inline frames) to represent new pages inside a main page. They can be either multiple iframes or nested iframes. The iframes are indicated with an iframe tag, such as <iframe>...</iframe>
.
It's easy to handle iframes when a user discovers all the iframes available in a web page. Google Chrome's Developer debugging tool is used to check the availability of iframes. The following figure is an example of nested iframes:
To handle iframes, it's important to switch into and move out of an iframe to the main frame. The following is the syntax for switching iframes:
driver.switchTo().frame()
The following code snippet is a real-time example of switching iframes to locate elements.
driver.switchTo().frame(driver.findElement(By.locatorType("iframe[id='Value']")));
To access an iframe located outside the present iframe, it is essential to terminate the current iframe. Closing an iframe lets you move from the current iframe to the main content. To do so, follow the following syntax:
driver.switchTo().defaultContent(); // close iFrame
To locate an element in a web page with nested iframes, try the switchTo()
method multiple times to switch between iframes. The following code snippet is a sample nested iframe structure, followed by a snippet for handling multiple iframes:
<iframe ...> <iframe ...> <iframe ...> </iframe> </iframe> </iframe>
The following is a snippet that handles the structured nested iframes:
driver.switchTo().frame(driver.findElement(By.locatorType("iframe[id='1']"))); driver.switchTo().frame(driver.findElement(By.locatorType("iframe[id='2']"))); driver.switchTo().frame(driver.findElement(By.locatorType("iframe[id='3']"))); driver.switchTo().defaultContent(); driver.switchTo().defaultContent(); driver.switchTo().defaultContent();
Obtain the iframe position to handle iframes without id
or name
. To do so, use the following syntax:
driver.switchTo().frame(value);
The following iframes are available at the first and second positions:
driver.switchTo().frame(0); driver.switchTo().frame(1);
Some of the most popular UI-based automation tools, such as AutoIT, Sikuli, and Java Robot, are quite easy to integrate with Selenium WebDriver tests. However, it is difficult to implement and operate these tools on varying screen resolutions, handling Selenium Grid, cross-browser tests, and more. In general, the Selenium WebDriver API doesn't support native OS and browser pop-up handling. The browser profile is a set of customized browser instances, which is an alternative choice to handle these pop-ups.
The Java.awt.Robot
library is a Java library file that supports Selenium WebDriver to interact with web applications through control over mouse and keyboard actions.
Let's discuss the following example to perform a simple Google search using Java Robot and Selenium WebDriver:
import java.awt.Robot; import java.awt.event.KeyEvent; import java.lang.reflect.Field; public class classname { private WebDriver driver; private String baseUrl; @Test public void Test01() throws Exception { driver = new FirefoxDriver(); driver.get("https://www.google.com"); Robot r = new Robot(); driver.findElement(By.name("q")).click(); Thread.sleep(4000); typeKeys("Prashanth Sams", r); } public static void typeKeys(String str, Robot r) { for (int i = 0; i < str.length(); i++) { typeCharacter(r, "" + str.charAt(i)); } } public static void typeCharacter(Robot robot, String letter) { try { boolean upperCase = Character.isUpperCase(letter.charAt(0)); String variableName = "VK_" + letter.toUpperCase(); Class c = KeyEvent.class; Field field = c.getField(variableName); int keyCode = field.getInt(null); robot.delay(1000); if (upperCase) robot.keyPress(KeyEvent.VK_SHIFT); robot.keyPress(keyCode); robot.keyRelease(keyCode); if (upperCase) robot.keyRelease(KeyEvent.VK_SHIFT); } catch (Exception e) { System.out.println(e); } }
Multiplatform support, such as running tests through Selenium Grid with varying screen resolutions, is not feasible on Java Robot, and it always depends on the screen (x,y) coordinates. In general, the browser pop-up is in the form of a download dialog box, upload dialog box, advertisements, and more.
Let's see how to save a file from a browser download pop-up as shown in the following screenshot:
The prerequisites for the next code snippet to execute are:
Make sure that all the preceding specifications are met before executing the following piece of code. Here, it is mandatory to customize location coordinates for screens with different resolutions. In this example, the Java Robot
class is intended to choose Save file on clicking the radio button and finally clicking on the OK button:
Robot r = new Robot(); /** click Save File **/ r.mouseMove(787, 544); //move to co-ordinate Location r.mousePress(InputEvent.BUTTON1_MASK); //Left Mouse click-Press r.mouseRelease(InputEvent.BUTTON1_MASK); //Left Mouse click-Release r.delay(5); //wait for 5 millisecs /** click ok **/ r.mouseMove(10322, 641); //move to co-ordinate Location r.mousePress(InputEvent.BUTTON1_MASK); //Left Mouse click-Press r.mouseRelease(InputEvent.BUTTON1_MASK); //Left Mouse click-Release
Screen capture provides explicit test reports by logging test failures as screenshots. Furthermore, the Java Robot
class is also helpful in taking instant screenshots on each test failure. The following is the code for this method:
Robot r = new Robot();
BufferedImageimg = r.createScreenCapture(new Rectangle(0, 0, 100, 100));
File path = new File("C://screen.jpg");
ImageIO.write(img, "JPG", path);
There are several ways to capture the screen. Let's see some of the helpful methods, which are as follows:
WebDriver augmentedDriver = new Augmenter().augment(driver);
File screenshot = ((TakesScreenshot)augmentedDriver).
getScreenshotAs(OutputType.FILE);
String path = "/Users/prashanth_sams/Desktop/" + screenshot.getName();
FileUtils.copyFile(screenshot, new File(path));
Robot
as follows:java.awt.Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
Robot r = new Robot();
BufferedImage img = r.createScreenCapture(new Rectangle(size));
File path = new File("C://screen.jpg");
ImageIO.write(img, "JPG", path);
In the following list are some of the most important Robot
class functions that are eventually valuable while integrating Selenium WebDriver:
Robot r = new Robot(); r.mouseMove(500, 500); //move to co-ordinate Location r.mousePress(InputEvent.BUTTON1_MASK); //Left Mouse click-Press r.mouseRelease(InputEvent.BUTTON1_MASK); //Left Mouse click–Release r.mousePress(InputEvent.BUTTON2_MASK); //Middle Mouse click-Press r.mouseRelease(InputEvent.BUTTON2_MASK); //Middle Mouse click–Release r.mousePress(InputEvent.BUTTON3_MASK); //Right Mouse click-Press r.mouseRelease(InputEvent.BUTTON3_MASK); // Right Mouse click-Release r.mouseWheel(7); //Scroll Mouse r.getPixelColor(500, 100); //Get Pixel color-RBG MouseInfo.getPointerInfo().getLocation(); //Get Current Mouse Location Toolkit.getDefaultToolkit().getScreenSize(); //Get Screen Resolution-Dimension r.createScreenCapture(new Rectangle(size)); //Screen capture r.keyPress(KeyEvent.VK_ENTER); //Press Enter Key r.keyRelease(KeyEvent.VK_ENTER); //Release Enter Key r.delay(5); //wait for certain milliseconds
Refer to the following link to check all the Java Robot keyboard actions:
https://sites.google.com/site/seleniumworks/java_robot
Mofiki's Coordinate Finder lets you find the instant screen coordinates of the current mouse pointer location.
Whenever a user tries to download a file, they get a download dialog box that keeps on asking whether the file has to be saved or opened with an application. The simplest way to ignore these browser pop-ups and to save files is through browser profiles. It can be done either manually or through setting up Firefox profile preferences.
The following couple of methods let you download files locally without any risk:
FirefoxProfile profile = new FirefoxProfile();
"browser.helperApps.neverAsk.saveToDisk"
Refer to the following code to avoid the Firefox browser's default download pop-up through setPreferences
:
FirefoxProfile profile = new FirefoxProfile();
String path = "C:\Test\";
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.download.dir", path);
profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/msword, application/csv, application/ris, text/csv, image/png, application/pdf, text/html, text/plain, application/zip, application/x-zip, application/x-zip-compressed, application/download, application/octet-stream");
profile.setPreference("browser.download.manager.showWhenStarting", false);
profile.setPreference("browser.download.manager.focusWhenStarting", false);
profile.setPreference("browser.download.useDownloadDir", true);
profile.setPreference("browser.helperApps.alwaysAsk.force", false);
profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
profile.setPreference("browser.download.manager.closeWhenDone", true);
profile.setPreference("browser.download.manager.showAlertOnComplete", false);
profile.setPreference("browser.download.manager.useWindow", false);
profile.setPreference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", false);
profile.setPreference("pdfjs.disabled", true);
driver = new FirefoxDriver(profile);