How to Switch Between Frames in Selenium WebDriver

HOME

Switching between frames in Selenium can be necessary when dealing with web pages that use iframes. The methods to switch between frames allow you to interact with elements within those frames

1) Switching by Name or ID

If the frame or iframe has an id or name attribute, we can switch the frames using name or ID. If the name or ID is not unique on the page, then the first one found will be switched to.

//switch To IFrame using name or id
driver.findElement(By.name("iframe1-name"));

//Switch to the frame
driver.switchTo().frame(iframe);

2) Switching by WebElement

We can find the frame using any selector and switch to it.

WebElement frameElement = driver.findElement(By.id("frameId"));
driver.switchTo().frame(frameElement);

3) Switching by Index

Switching between the frames can be done by Index also.

//switch To IFrame using index
driver.switchTo().frame(0);
//leave frame
driver.switchTo().defaultContent();

Let us explain frame switchching with an example:-

1) Launch new Browser and open https://demoqa.com/frames
2) Switch iFrame using any of locator strategy
3) Switch back to main content
4) Switch iFrame using index
5) Close the window

The program for the above scenario is shown below:

package com.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;


public class iFrame_Demo {

    public static void main(String[] args) {

        ChromeOptions options = new ChromeOptions();
        WebDriver driver = new ChromeDriver(options);
        driver.manage().window().maximize();
        driver.get("https://demoqa.com/frames");

        //Switch iFrame using any of locator strategy
        WebElement iframeElement = driver.findElement(By.id("frame1"));
        driver.switchTo().frame(iframeElement);
        String Frame_1 = driver.findElement(By.id("sampleHeading")).getText();
        System.out.println("Switch by locator:" + Frame_1);

        //Switch back to the main window
        driver.switchTo().defaultContent();
        String mainPage = driver.findElement(By.xpath("//*[@id='framesWrapper']/h1")).getText();
        System.out.println("Back to Main page :" + mainPage);

        //Switch iFrame using index
         driver.switchTo().frame(1);
        String Frame_2 = driver.findElement(By.id("sampleHeading")).getText();
        System.out.println("Switch by Index :" + Frame_2);

        //quit the browser
        driver.quit();
    }
}

    Congratulations. We have learnt about window switching in Selenium. I hope you find this tutorial helpful. Happy Learning!!

    Serenity Testing on Different Browsers

    HOME

    mvn clean verify -Denvironment=chrome
    
    environments {
      chrome {
        webdriver {
          driver = chrome
          autodownload = true
          capabilities {
            browserName = "chrome"
            acceptInsecureCerts = true
            "goog:chromeOptions" {
              args = ["test-type", "ignore-certificate-errors", "headless", "--window-size=1000,800"
                "incognito", "disable-infobars", "disable-gpu", "disable-default-apps", "disable-popup-blocking"]
            }
          }
        }
      }
      edge {
        webdriver {
          capabilities {
            browserName = "MicrosoftEdge"
            "ms:edgeOptions" {
              args = ["test-type", "ignore-certificate-errors", "headless",
                "incognito", "disable-infobars", "disable-gpu", "disable-default-apps", "disable-popup-blocking"]
            }
          }
        }
      }
      firefox {
        webdriver {
          capabilities {
            browserName = "firefox"
            pageLoadStrategy = "normal"
            acceptInsecureCerts = true
            unhandledPromptBehavior = "dismiss"
            strictFileInteractability = true
    
            "moz:firefoxOptions" {
              args = ["-headless"],
              prefs {
                "javascript.options.showInConsole": false
              },
              log {"level": "info"},
            }
          }
        }
      }
    }
    

    mvn clean verify -Denvironment="chrome"
    

    mvn clean verify -Denvironment="firefox"
    

    mvn clean verify -Denvironment="edge"
    

    How to handle token expiration and automatic refreshing of tokens in REST Assured?

    HOME

    <dependencies>
     
           <!-- Rest Assured Dependency -->
          <dependency>
             <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>5.4.0</version>
            <scope>test</scope>
          </dependency>
    
          <!-- JSON path Dependency -->
          <dependency>
             <groupId>io.rest-assured</groupId>
             <artifactId>json-path</artifactId>
             <version>5.4.0</version>
             <scope>test</scope>
          </dependency>
     
            <!-- TestNG Dependency-->
          <dependency>
              <groupId>org.testng</groupId>
             <artifactId>testng</artifactId>
             <version>7.8.0</version>
             <scope>test</scope>
           </dependency>
     
    </dependencies>
    

    import io.restassured.RestAssured;
    import io.restassured.response.Response;
    
    import java.time.Instant;
    
    public class TokenGeneration {
    
        private static String accessToken;
        private static Instant tokenExpiryTime;
        Response response;
        int expiresIn;
    
        // Method to obtain initial token
        public static String getAccessToken() {
            if (accessToken == null || isTokenExpired()) {
                refreshAccessToken();
            }
            return accessToken;
        }
    
        // Method to check if the token is expired
        private static boolean isTokenExpired() {
            return tokenExpiryTime == null || Instant.now().isAfter(tokenExpiryTime);
        }
    
        // Method to refresh token
        private static void refreshAccessToken() {
                response = RestAssured.given()
                .contentType("application/x-www-form-urlencoded")
                .formParam("grant_type", "client_credentials")
                .formParam("client_id", "your-client-id")
                .formParam("client_secret", "your-client-secret")
                .post("https://your-auth-server.com/oauth/token");
    
            accessToken = response.jsonPath().getString("access_token");
            expiresIn = response.jsonPath().getInt("expires_in");
            tokenExpiryTime = Instant.now().plusSeconds(expiresIn);
    
            System.out.println("Access Token: " + accessToken);
            System.out.println("Token Expiry Time: " + tokenExpiryTime);
        }
    }
    

    tokenExpiryTime == null || Instant.now().isAfter(tokenExpiryTime);
    
    tokenExpiryTime = Instant.now().plusSeconds(expiresIn);
    
    import static io.restassured.RestAssured.given;
    import org.testng.annotations.Test;
    
    public class ApiTest {
    
            String token = TokenGeneration.getAccessToken();
            Response response;
    
           @Test
           public getResponse() {
             response = given()
                    .auth().oauth2(token)
                    .when()
                    .get("https://example.com/protected/resource")
                    .then()
                    .statusCode(200)
                    .extract().response();
    
            System.out.println("Response: " + response.asString());
        }
    }
    

    private static final long TOKEN_EXPIRY_BUFFER_SECONDS = 60;  // 1 minute buffer
        
    private static boolean isTokenExpired() {
            return tokenExpiryTime == null || Instant.now().isAfter(tokenExpiryTime.minusSeconds(TOKEN_EXPIRY_BUFFER_SECONDS));
     }
    

    TestNG Multiple Choice Answers

    HOME












    <!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >
    <suite name="SampleSuite">
        <test name="SampleTest">
            <classes>
                <class name="com.example.MyTestClass" />
            </classes>
        </test>
    </suite>
    













    25 Useful TestNG Multiple-Choice Questions | Self-Test Your Knowledge

    HOME

    Answer


    Answer


    Answer


    Answer


    Answer


    Answer


    Answer


    Answer


    Answer


    Answer


    Answer


    Answer


    Answer


    Answer


    Answer


    Answer


    Answer


    Answer


    Answer


    Answer


    Answer


    Answer


    Answer


    Answer


    Answer

    How to test ToolTip in Selenium

    HOME

     WebElement elementWithTooltip = driver.findElement(By.id("toolTipButton"));
    

    Actions actions = new Actions(driver);
    actions.moveToElement(elementWithTooltip).perform();
    

    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
    WebElement tooltip = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(text(),'You hovered over the Button')]")));
    
      if (expectedTooltipText.equals(actualTooltipText)) {
                System.out.println("Tooltip text is correct!");
            } else {
                System.out.println("Tooltip text is incorrect!");
     }
    

    package com.example;
    
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;
    import org.openqa.selenium.interactions.Actions;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.WebDriverWait;
    
    import java.time.Duration;
    
    public class TooltipTest_Demo {
    
        static WebDriver driver;
        static String expectedTooltipText = "You hovered over the Button";
        static String actualTooltipText;
    
        public static void main(String[] args) {
    
            ChromeOptions options = new ChromeOptions();
            driver = new ChromeDriver(options);
            driver.manage().window().maximize();
    
            driver.get("https://demoqa.com/tool-tips");
    
            // Locate the element with the tooltip
            WebElement elementWithTooltip = driver.findElement(By.id("toolTipButton"));
    
            // Perform hover action using Actions class
            Actions actions = new Actions(driver);
            actions.moveToElement(elementWithTooltip).perform();
    
            // Wait for the tooltip to be visible
            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
            WebElement tooltip = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(text(),'You hovered over the Button')]")));
    
            // Check the tooltip text
            actualTooltipText = tooltip.getText();
            System.out.println("Actual Tooltip Text: " + actualTooltipText);
    
            if (expectedTooltipText.equals(actualTooltipText)) {
                System.out.println("Tooltip text is correct!");
            } else {
                System.out.println("Tooltip text is incorrect!");
            }
    
            driver.quit();
        }
    
    }
    

    How to compare JSON File with JSON Response

    HOME

    <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.13.2</version>
          <scope>test</scope>
        </dependency>
    
        <dependency>
          <groupId>io.rest-assured</groupId>
          <artifactId>rest-assured</artifactId>
          <version>5.4.0</version>
          <scope>test</scope>
        </dependency>
    
        <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.11.3</version>
        </dependency>
    </dependencies>
    

    package com.example;
    
    import io.restassured.RestAssured;
    import io.restassured.response.Response;
    import com.fasterxml.jackson.databind.JsonNode;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.junit.Assert;
    import org.junit.Test;
    
    import java.io.File;
    import java.io.IOException;
    
    public class JsonFileComparison {
    
        @Test
        public void compareResponse() throws IOException {
    
            // Path to the JSON file
            File jsonFile = new File("src/test/resources/expectedUser.json");
    
            // Read JSON content from file
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonFromFile = objectMapper.readTree(jsonFile);
    
            // Make an API call
            Response response = RestAssured.given().when().get("https://reqres.in/api/users/3").then().extract().response();
            String expectedResponse = response.getBody().asString();
            System.out.println("Response is : " + expectedResponse);
    
            // Verify the status code
            response.then().statusCode(200);
    
            // Read JSON content from response
            JsonNode jsonFromResponse = objectMapper.readTree(expectedResponse);
    
            Assert.assertEquals(jsonFromFile, jsonFromResponse);
    
            // Compare JSON content
            if (jsonFromFile.equals(jsonFromResponse)) {
                System.out.println("JSON from file matches JSON from response");
            } else {
                System.out.println("JSON content does not match");
            }
        }
    }
    

    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode jsonFromFile = objectMapper.readTree(jsonFile);
    

    Response response = RestAssured.given().when().get("https://reqres.in/api/users/3").then().extract().response();
    String expectedResponse = response.getBody().asString();
    System.out.println("Response is : " + expectedResponse);
    
    // Verify the status code
    response.then().statusCode(200);
    

    JsonNode jsonFromResponse = objectMapper.readTree(expectedResponse);
    
     Assert.assertEquals(jsonFromFile, jsonFromResponse);
    

    Fluent Wait in Serenity

    HOME

    In the previous tutorials, I explained the Implicit Wait in Serenity and Explicit Wait in Serenity. This tutorial will explain the Fluent Wait in Serenity.

    What is Fluent Wait?

    Fluent waits provide more flexibility, allowing us to specify polling intervals and ignore specific exceptions during the wait time.  Fluent Wait not only lets you specify the maximum amount of time to wait for a condition but also allows you to define the frequency with which the condition is checked and to ignore specific exceptions during the wait time.

    Below is the example of Fluent wait.

    import net.serenitybdd.annotations.DefaultUrl;
    import net.serenitybdd.annotations.Managed;
    import net.serenitybdd.core.annotations.findby.FindBy;
    import net.serenitybdd.core.pages.PageObject;
    import net.serenitybdd.core.pages.WebElementFacade;
    import net.serenitybdd.junit.runners.SerenityRunner;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.openqa.selenium.ElementNotInteractableException;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.support.ui.FluentWait;
    
    import java.time.Duration;
    import java.util.function.Function;
    
    @RunWith(SerenityRunner.class)
    @DefaultUrl("http://the-internet.herokuapp.com/dynamic_loading/1")
    public class FluentWait_Demo extends PageObject {
    
        @Managed
        WebDriver driver;
    
        @FindBy(xpath = "//*[@id='start']/button")
        WebElementFacade startButton;
    
    
        @FindBy(xpath = "//*[@id='finish']/h4")
        WebElementFacade pageText;
    
        @Test
        public void fluentWaitDemo() throws InterruptedException {
    
            open();
            startButton.click();
            waitForElementWithFluentWait(pageText);
    
        }
    
        public void waitForElementWithFluentWait(WebElement pageText) {
            FluentWait wait = new FluentWait<>(getDriver())
                    .withTimeout(Duration.ofSeconds(10))
                    .pollingEvery(Duration.ofSeconds(2))
                    .ignoring(ElementNotInteractableException.class);
    
            wait.until((Function<WebDriver, Boolean>)
                    driver -> pageText.isDisplayed());
    
            System.out.println("Text :" + pageText.getText());
            System.out.println("Fluent Time defined for the test (in seconds) :" + getWaitForTimeout().toSeconds());
        }
    }
    

    public void waitForElementWithFluentWait(WebElement pageText) {
            FluentWait wait = new FluentWait<>(getDriver())
                    .withTimeout(Duration.ofSeconds(10))
                    .pollingEvery(Duration.ofSeconds(2))
                    .ignoring(ElementNotInteractableException.class);
    
           wait.until(driver -> pageText.isDisplayed());
    
            System.out.println("Text :" + pageText.getText());
            System.out.println("Fluent Time defined for the test (in seconds) :" + getWaitForTimeout().toSeconds());
        }
    

    We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

    Appending Data to Excel with Python using openpyxl

    HOME

    pip install openpyxl
    

    workbook = load_workbook("C:\\Users\\Vibha\\Automation\\SearchInBing.xlsx")
    

    sheet = workbook.active
    

    new_data =[
        ["Scrum Master", "5-10 Years", "35K"],
        ["Consultatnt", "8-12 Years", "37K"]
    ]
    

    last_row = sheet.max_row + 1
    

    for i, row in enumerate(new_data, start=last_row):
        for j, value in enumerate(row, start=1):
            sheet.cell(row=i, column=j, value=value)
    

    workbook.save("C:\\Users\\Vibha\\Automation\\SearchInBing.xlsx")
    

    from openpyxl.reader.excel import load_workbook
    from openpyxl.styles import Font
    
    
    #Load the workbook
    workbook = load_workbook("C:\\Users\\ykv12\\Documents\\Vibha\\Automation\\SearchInBing.xlsx")
    
    sheet = workbook.active
    
    #Sample data
    new_data =[
        ["Scrum Master", "5-10 Years", "35K"],
        ["Consultatnt", "8-12 Years", "37K"]
    ]
    
    #Append the new data to the sheet
    last_row = sheet.max_row + 1
    for i, row in enumerate(new_data, start=last_row):
        for j, value in enumerate(row, start=1):
            sheet.cell(row=i, column=j, value=value)
    
    #Save the workbook
    workbook.save("C:\\Users\\ykv12\\Documents\\Vibha\\Automation\\SearchInBing.xlsx")
    
    print("Data is appended in the Excel file successfully")
    

    What is CucumberOptions in Cucumber?

    HOME

    mvn clean test -Dcucumber.options="--tags @smoke --plugin pretty"
    

    import org.junit.runner.RunWith;
    import io.cucumber.junit.Cucumber;
    import io.cucumber.junit.CucumberOptions;
    
    @RunWith(Cucumber.class)
    @CucumberOptions(
             features = "src/test/resources/features",
             glue = "com.mycompany.stepdefinitions",
             plugin = {"pretty", "html:target/cucumber-reports.html", "json:target/cucumber.json"},
             tags = "@smoke",
             monochrome = true,
             dryRun = false
         )
    
    public class RunCucumberTests {
    }
    

    cucumber.features=src/test/resources/features
    cucumber.glue=com.mycompany.stepdefinitions
    cucumber.plugin=pretty, html:target/cucumber-reports.html, json:target/cucumber.json
    cucumber.tags=@smoke
    

    import org.junit.runner.RunWith;
    import io.cucumber.junit.Cucumber;
    import io.cucumber.junit.CucumberOptions;
    
    @RunWith(Cucumber.class)
    @CucumberOptions( features = "src/test/resources/features",
        glue = "com.mycompany.stepdefinitions",
        plugin = {"pretty", "html:target/cucumber-reports.html", "json:target/cucumber.json"},
        tags = "@smoke",
        monochrome = true,
        dryRun = false,
        strict = true,
        name = "Login functionality"  )
    
    public class RunCucumberTest {
    }