Saturday, April 22, 2017

Switching between multiple frames in selenium


There can be multiple iframes in a webPage. To perform action on webelements in a frame, we need to first identify the frame and then perform action on the element.
We can switch to a particular frame based on the below identifiers:


By Index: The index depends on the order of frame in the Page. A numeric value is assigned to the frame based on the order in which it appears in the page.

driver.SwitchTo().Frame(0);

By Name: We can switch to a frame based on the name of the frame.

driver.SwitchTo().Frame("FrameName");

By Id: We can switch to a frame based on the id defined for the frame

driver.SwitchTo().Frame("FrameId");

Switch to a frame by locator for WebElement. In the below example frameElement is the locator for the frame

driver.switchTo().frame(frameElement);

e.g: 

driver.SwitchTo().Frame(driver.FindElement(By.CssSelector(cssfortheelement)));


Frame inside frames: There can be scenario in which there are frame inside of the parent frame.Please note in case of frame inside frame, we need to first switch to the outer frame, and then switch to the inner frame to perform action on the webelement.


To acess the main webPage and come out of the frame, below code is used

driver.SwitchTo().DefaultContent()

Friday, April 21, 2017

How to get text of an alert message in Selenium Webdriver: Mini-blogs

An alert message appears at times to notify the users of the alert as shown below. Using selenium webdriver, we can capture the text in the alert message using selenium web driver.


Using below two lines of code, we can get the alert message.


Alert alert = driver.switchTo().alert();
alert.getText();

Saturday, April 8, 2017

How to identify and close window alert using selenium

At times in browser,Alert box with a specified message and an OK button is displayed to ensure information comes through to the user. 

Alert box prevents the user from accessing other parts of the page until the box is closed. An alert is displayed is as shown below:

an example of alert window

While automating the web application, we can handle the pop up using alert Interface
The alert() method displays an alert box with a specified message and an OK button.

Below code shows how to close an window alert pop up using selenium:



public void Accept_Alert_Message() {
    try {
  //Using webdriver wait, we will wait for the alert
  //to appear before performing action on the alert
        WebDriverWait driverwait = new WebDriverWait(driver, 5);
        driverwait.until(ExpectedConditions.alertIsPresent());
  //switch to the alert element
        Alert alert = driver.switchTo().alert();
  //accept the alert displayed
        alert.accept();
  //switch to the default content
  driver.switchTo().defaultContent();
    } catch (Exception e) {
     // in case alert is not displayed, the code will go to catch loop
    }
}