Read PDF Files with Selenium in Java

HOME

  <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>4.24.0</version>
    </dependency>

    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.16.1</version>
    </dependency>

    <dependency>
      <groupId>org.apache.pdfbox</groupId>
      <artifactId>pdfbox</artifactId>
      <version>3.0.3</version>
    </dependency>

 String downloadFilepath = System.getProperty("user.dir") + File.separator + "downloads";

        ChromeOptions options = new ChromeOptions();
        Map<String, Object> prefs = new HashMap<>();
        prefs.put("plugins.always_open_pdf_externally", true);
        prefs.put("download.default_directory", downloadFilepath);
        options.setExperimentalOption("prefs", prefs);

        WebDriver driver = new ChromeDriver(options);
        driver.manage().window().maximize();
        driver.get("https://freetestdata.com/document-files/pdf/");

        // Locate and click the download link or button if necessary
        WebElement downloadLink = driver.findElement(By.xpath("//*[@class=\"elementor-button-text\"]"));
        downloadLink.click();

        //Wait for download to complete
        File downloadedFile = new File(downloadFilepath + "/Free_Test_Data_100KB_PDF.pdf");
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
        wait.until((ExpectedCondition<Boolean>) wd -> downloadedFile.exists());

        // Check if the file exists
        if (downloadedFile.exists()) {
            System.out.println("File is downloaded!");
        } else {
            System.out.println("File is not downloaded.");
        }

File file = new File("Path of Document");   
PDDocument doc = Loader.loadPDF(file);   
PDFTextStripper pdfStripper = new PDFTextStripper();  
String text = pdfStripper.getText(doc);  

import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
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.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

public class ReadPDF_Chrome_Demo {

    public static void main(String[] args) throws InterruptedException {

        String downloadFilepath = System.getProperty("user.dir") + File.separator + "chrome_downloads";

        ChromeOptions options = new ChromeOptions();
        Map<String, Object> prefs = new HashMap<>();
        prefs.put("plugins.always_open_pdf_externally", true);
        prefs.put("download.default_directory", downloadFilepath);
        options.setExperimentalOption("prefs", prefs);

        WebDriver driver = new ChromeDriver(options);
        driver.manage().window().maximize();
        driver.get("https://freetestdata.com/document-files/pdf/");

        // Locate the download link/button and click and wait for the download to complete
        WebElement downloadLink = driver.findElement(By.xpath("//*[@class='elementor-button-text']"));
        downloadLink.click();

        //Wait for download to complete
        File downloadedFile = new File(downloadFilepath + "/Free_Test_Data_100KB_PDF.pdf");
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
        wait.until((ExpectedCondition<Boolean>) wd -> downloadedFile.exists());
        
        // Check if the file exists
        if (downloadedFile.exists()) {
            System.out.println("File is downloaded!");
        } else {
            System.out.println("File is not downloaded.");
        }

        driver.quit();

        // Read the downloaded PDF using PDFBox
        PDDocument document = null;
        try {
            document = Loader.loadPDF(downloadedFile);
            PDFTextStripper pdfStripper = new PDFTextStripper();
            String text = pdfStripper.getText(document);
            document.close();

            // Print the PDF text content
            System.out.println("Text in PDF: ");
            System.out.println(text);
        } catch (IOException e) {
            System.err.println("An error occurred while loading or reading the PDF file: " + e.getMessage());
            e.printStackTrace();
        }

    }

}

### Summary

Download PDF in Chrome with Selenium Java

HOME

 String downloadFilepath = System.getProperty("user.dir") + File.separator + "downloads";
ChromeOptions options = new ChromeOptions();
Map<String, Object> prefs = new HashMap<>();
prefs.put("plugins.always_open_pdf_externally", true);
prefs.put("download.default_directory", downloadFilepath);
options.setExperimentalOption("prefs", prefs);
prefs.put("plugins.always_open_pdf_externally", true) 
prefs.put("download.default_directory", System.getProperty("user.dir") + File.separator + "downloads");
options.setExperimentalOption("prefs", prefs);
WebDriver driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.get("https://freetestdata.com/document-files/pdf/");
WebElement downloadLink = driver.findElement(By.xpath("//*[@class=\"elementor-button-text\"]"));
downloadLink.click();
Thread.sleep(5000); 
 File downloadedFile = new File(downloadFilepath + "/Free_Test_Data_100KB_PDF.pdf");
        if (downloadedFile.exists()) {
            System.out.println("File is downloaded!");
        } else {
            System.out.println("File is not downloaded.");
      }
driver.quit();
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 java.io.File;
import java.util.HashMap;
import java.util.Map;

public class DownloadPDF_Chrome_Demo {

    public static void main(String[] args) throws InterruptedException {

        String downloadFilepath = System.getProperty("user.dir") + File.separator + "downloads";

        ChromeOptions options = new ChromeOptions();
        Map<String, Object> prefs = new HashMap<>();
        prefs.put("plugins.always_open_pdf_externally", true);
        prefs.put("download.default_directory", downloadFilepath);
        options.setExperimentalOption("prefs", prefs);

        WebDriver driver = new ChromeDriver(options);
        driver.manage().window().maximize();
        driver.get("https://freetestdata.com/document-files/pdf/");

        // Locate and click the download link or button if necessary
        WebElement downloadLink = driver.findElement(By.xpath("//*[@class=\"elementor-button-text\"]"));
        downloadLink.click();

        // Wait for the download to complete
        Thread.sleep(5000); 
        
        // Check if the file exists
        File downloadedFile = new File(downloadFilepath + "/Free_Test_Data_100KB_PDF.pdf");
        if (downloadedFile.exists()) {
            System.out.println("File is downloaded!");
        } else {
            System.out.println("File is not downloaded.");
        }

        driver.quit();
    }
}

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!!

    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();
        }
    
    }
    

    Keyword Driven Framework Tutorial – Selenium

    HOME

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.example</groupId>
      <artifactId>KeywordDrivenFramework</artifactId>
      <version>1.0-SNAPSHOT</version>
      <packaging>jar</packaging>
    
      <name>KeywordDrivenFramework</name>
      <url>http://maven.apache.org</url>
    
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <selenium.version>4.21.0</selenium.version>
        <testng.version>7.10.2</testng.version>
        <poi.version>5.2.5</poi.version>
        <poi.ooxml.version>5.2.5</poi.ooxml.version>
        <commons.version>2.16.1</commons.version>
        <maven.surefire.plugin.version>3.2.5</maven.surefire.plugin.version>
        <maven.compiler.plugin.version>3.13.0</maven.compiler.plugin.version>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
      </properties>
    
      <dependencies>
        <dependency>
          <groupId>org.seleniumhq.selenium</groupId>
          <artifactId>selenium-java</artifactId>
          <version>${selenium.version}</version>
        </dependency>
    
        <dependency>
          <groupId>org.testng</groupId>
          <artifactId>testng</artifactId>
          <version>${testng.version}</version>
        </dependency>
    
        <dependency>
          <groupId>org.apache.poi</groupId>
          <artifactId>poi</artifactId>
          <version>${poi.version}</version>
        </dependency>
    
        <dependency>
          <groupId>org.apache.poi</groupId>
          <artifactId>poi-ooxml</artifactId>
          <version>${poi.ooxml.version}</version>
        </dependency>
    
        <dependency>
          <groupId>commons-io</groupId>
          <artifactId>commons-io</artifactId>
          <version>${commons.version}</version>
        </dependency>
      </dependencies>
    
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>${maven.compiler.plugin.version}</version>
            <configuration>
              <source>${maven.compiler.source}</source>
              <target>${maven.compiler.target}</target>
            </configuration>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>${maven.surefire.plugin.version}</version>
            <configuration>
              <suiteXmlFiles>
                <suiteXmlFile>testng.xml</suiteXmlFile>
              </suiteXmlFiles>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </project>
    

    package com.example.pages;
    
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.support.PageFactory;
    
    public class BasePage {
        public WebDriver driver;
    
        public BasePage(WebDriver driver) {
            this.driver = driver;
            PageFactory.initElements(driver,this);
        }
    
    }
    

    package com.example.keywords;
    
    import com.example.utils.ExcelUtils;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.support.FindBy;
    
    public class LoginPageKeywords extends BasePage{
    
        public LoginPageKeywords(WebDriver driver) {
            super(driver);
    
        }
    
        @FindBy(name = "username")
        public WebElement userName;
    
        @FindBy(name = "password")
        public WebElement password;
    
        @FindBy(xpath = "//*[@class='oxd-form']/div[1]/div/span")
        public WebElement missingUsernameErrorMessage;
    
        @FindBy(xpath = "//*[@class='oxd-form']/div[2]/div/span")
        public WebElement missingPasswordErrorMessage;
    
        @FindBy(xpath = "//*[@class='oxd-form']/div[3]/button")
        public WebElement loginBtn;
    
        @FindBy(xpath = "//*[@id='app']/div[1]/div/div[1]/div/div[2]/div[2]/div/div[1]/div[1]/p")
        public  WebElement errorMessage;
    
    
        public void enterUsername(String strUserName) {
            userName.sendKeys(strUserName);
        }
    
        public void enterPassword(String strPassword) {
            password.sendKeys(strPassword);
        }
    
        public void login() {
            loginBtn.click();
        }
    
        public void login(String strUserName, String strPassword) {
    
            userName.sendKeys(strUserName);
            password.sendKeys(strPassword);
        }
    
        public String getMissingUsernameText() {
            return missingUsernameErrorMessage.getText();
        }
    
        public String getMissingPasswordText() {
            return missingPasswordErrorMessage.getText();
        }
    
        public String getErrorMessage() {
            return errorMessage.getText();
        }
    
        public LoginPageKeywords saveTestResults(int row, int column) {
            ExcelUtils.rowNumber = row ;
            ExcelUtils.columnNumber = column;
            return this;
        }
    
    }
    

    package com.example.keywords;
    
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.support.FindBy;
    
    public class HomePageKeywords extends BasePage {
    
        public HomePageKeywords(WebDriver driver) {
            super(driver);
    
        }
    
        @FindBy(xpath = "//*[@id='app']/div[1]/div[1]/header/div[1]/div[1]/span/h6")
        public  WebElement homePageUserName;
    
        public String verifyHomePage() {
            return homePageUserName.getText();
        }
    }
    

    package com.example.utils;
    
    import org.apache.poi.ss.usermodel.DataFormatter;
    import org.apache.poi.xssf.usermodel.XSSFCell;
    import org.apache.poi.xssf.usermodel.XSSFRow;
    import org.apache.poi.xssf.usermodel.XSSFSheet;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    public class ExcelUtils {
    
    
        public static String testDataExcelPath = null; //Location of Test data excel file
        private static XSSFWorkbook excelWorkBook; //Excel WorkBook
        private static XSSFSheet excelWorkSheet; //Excel Sheet
        private static XSSFCell cell; //Excel cell
        private static XSSFRow row; //Excel row
        public static int rowNumber; //Row Number
        public static int columnNumber; //Column Number
        public static FileInputStream ExcelFile;
    
        public static DataFormatter formatter;
        public static FileOutputStream fileOut;
    
    
        // This method has two parameters: "Test data excel file name" and "Excel sheet name"
        // It creates FileInputStream and set excel file and excel sheet to excelWBook and excelWSheet variables.
        public static void setExcelFileSheet(String sheetName) throws IOException {
    
            testDataExcelPath = Constants.currentDir + Constants.resourcePath;
    
            // Open the Excel file
            ExcelFile = new FileInputStream(testDataExcelPath + Constants.testDataExcelFileName);
            excelWorkBook = new XSSFWorkbook(ExcelFile);
            excelWorkSheet = excelWorkBook.getSheet(sheetName);
    
        }
    
        //This method reads the test data from the Excel cell.
        public static String getCellData(int rowNum, int colNum) {
            cell = excelWorkSheet.getRow(rowNum).getCell(colNum);
            formatter = new DataFormatter();
            return formatter.formatCellValue(cell);
        }
    
        //This method takes row number as a parameter and returns the data of given row number.
        public static XSSFRow getRowData(int rowNum) {
            row = excelWorkSheet.getRow(rowNum);
            return row;
        }
    
        //This method gets excel file, row and column number and set a value to the that cell.
        public static void setCellData(String value, int rowNum, int colNum) throws IOException {
            row = excelWorkSheet.getRow(rowNum);
            cell = row.getCell(colNum);
            if (cell == null) {
                cell = row.createCell(colNum);
                cell.setCellValue(value);
            } else {
                cell.setCellValue(value);
            }
    
            // Write to the workbook
            fileOut = new FileOutputStream(testDataExcelPath + Constants.testDataExcelFileName);
            excelWorkBook.write(fileOut);
            fileOut.flush();
            fileOut.close();
        }
    }
    

    import com.example.tests.BaseTests;
    import org.openqa.selenium.WebDriver;
    import org.testng.ITestContext;
    import org.testng.ITestListener;
    import org.testng.ITestResult;
    import java.io.IOException;
    
    public class TestListener implements ITestListener {
    
        private static String getTestMethodName(ITestResult iTestResult) {
            return iTestResult.getMethod().getConstructorOrMethod().getName();
        }
    
        @Override
        public void onStart(ITestContext iTestContext) {
            System.out.println("I am in onStart method :" + iTestContext.getName());
        }
    
        @Override
        public void onFinish(ITestContext iTestContext) {
            System.out.println("I am in onFinish method :" + iTestContext.getName());
        }
    
        @Override
        public void onTestStart(ITestResult iTestResult) {
            System.out.println("I am in onTestStart method :" + getTestMethodName(iTestResult) + ": start");
        }
    
        @Override
        public void onTestSuccess(ITestResult iTestResult)  {
            System.out.println("I am in onTestSuccess method :" + getTestMethodName(iTestResult) + ": succeed");
            try {
                ExcelUtils.setCellData("PASSED", ExcelUtils.rowNumber, ExcelUtils.columnNumber);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    
        @Override
        public void onTestFailure(ITestResult iTestResult)  {
            System.out.println("I am in onTestFailure method :" + getTestMethodName(iTestResult) + " failed");
            try {
                ExcelUtils.setCellData("FAILED", ExcelUtils.rowNumber, ExcelUtils.columnNumber);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    
        @Override
        public void onTestSkipped(ITestResult iTestResult) {
            System.out.println("I am in onTestSkipped method :" + getTestMethodName(iTestResult) + ": skipped");
            try {
                ExcelUtils.setCellData("SKIPPED", ExcelUtils.rowNumber, ExcelUtils.columnNumber);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    
        @Override
        public void onTestFailedButWithinSuccessPercentage(ITestResult iTestResult) {
            System.out.println("Test failed but it is in defined success ratio " + getTestMethodName(iTestResult));
        }
    }
    

    package com.example.utils;
    
    public class Constants {
    
        public static final String testDataExcelFileName = "Test_Cases.xlsx"; //Global test data excel file
        public static final String currentDir = System.getProperty("user.dir");  //Main Directory of the project
        public static final String resourcePath = "\\src\\test\\resources\\";  //Main Directory of the project
        public static final String excelTestDataName = "LoginData";
    }
    
    

    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;
    import org.testng.annotations.AfterMethod;
    import org.testng.annotations.BeforeMethod;
    
    import java.time.Duration;
    
    public class BaseTests {
    
        public static WebDriver driver;
        public final static int TIMEOUT = 10;
    
        @BeforeMethod
        public void setup() {
    
            ChromeOptions options = new ChromeOptions();
            options.addArguments("--remote-allow-origins=*");
            options.addArguments("--no-sandbox");
            options.addArguments("--disable-dev-shm-usage");
            options.addArguments("--headless");
            driver = new ChromeDriver(options);
            driver.manage().window().maximize();
            driver.get("https://opensource-demo.orangehrmlive.com/");
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(TIMEOUT));
    
        }
    
        @AfterMethod
        public void tearDown() {
            driver.quit();
        }
    
    }
    

    package com.example.tests;
    
    import com.example.keywords.HomePageKeywords;
    import com.example.keywords.LoginPageKeywords;
    import com.example.utils.Constants;
    import com.example.utils.ExcelUtils;
    import com.example.utils.TestListener;
    import org.testng.Assert;
    import org.testng.annotations.BeforeTest;
    import org.testng.annotations.Listeners;
    import org.testng.annotations.Test;
    
    import java.io.IOException;
    
    @Listeners({TestListener.class })
    public class LoginPageTests extends BaseTests {
    
        String username;
        String password;
        String actualResponse;
        String expectedResponse;
    
    
        @BeforeTest
        public void setupTestData() throws IOException {
    
            System.out.println("Setup Test Data");
            ExcelUtils.setExcelFileSheet(Constants.excelTestDataName);
        }
    
        @Test
        public void validCredentials() throws IOException {
    
            username = ExcelUtils.getCellData(2,5);
            password = ExcelUtils.getCellData(3,5);
            expectedResponse = ExcelUtils.getCellData(5,6);
    
            LoginPageKeywords loginPage = new LoginPageKeywords(driver);
    
            loginPage.enterUsername(username);
            loginPage.enterPassword(password);
            loginPage.login();
    
            HomePageKeywords homePage = new HomePageKeywords(driver);
            actualResponse = homePage.verifyHomePage();
    
            ExcelUtils.setCellData(actualResponse,5,7);
            saveTestResults(5,8);
            Assert.assertEquals(actualResponse,expectedResponse);
    
        }
    
        @Test
        public void invalidCredentials() throws IOException {
    
            username = ExcelUtils.getCellData(9,5);
            password = ExcelUtils.getCellData(10,5);
            expectedResponse = ExcelUtils.getCellData(12,6);
    
            LoginPageKeywords loginPage = new LoginPageKeywords(driver);
    
            loginPage.enterUsername(username);
            loginPage.enterPassword(password);
            loginPage.login();
    
            actualResponse = loginPage.getErrorMessage();
    
            ExcelUtils.setCellData(actualResponse,12,7);
            saveTestResults(12,8);
            Assert.assertEquals(actualResponse,expectedResponse);
    
        }
    
    }
    

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
    <suite name="Keyword Driven Framework">
        <test name="Login Test">
            <classes>
                <class name="com.example.tests.LoginPageTests"/>
            </classes>
        </test> <!-- Test -->
    </suite> <!-- Suite -->
    

    mvn clean test
    

    Selenium Data Driven Framework Tutorial

    HOME

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.example</groupId>
      <artifactId>DataDrivenFramework</artifactId>
      <version>1.0-SNAPSHOT</version>
      <packaging>jar</packaging>
    
      <name>DataDrivenFramework</name>
      <url>http://maven.apache.org</url>
    
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <selenium.version>4.21.0</selenium.version>
        <testng.version>7.10.2</testng.version>
        <poi.version>5.2.5</poi.version>
        <poi.ooxml.version>5.2.5</poi.ooxml.version>
        <commons.version>2.16.1</commons.version>
        <maven.surefire.plugin.version>3.2.5</maven.surefire.plugin.version>
        <maven.compiler.plugin.version>3.13.0</maven.compiler.plugin.version>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
      </properties>
    
      <dependencies>
        <dependency>
          <groupId>org.seleniumhq.selenium</groupId>
          <artifactId>selenium-java</artifactId>
          <version>${selenium.version}</version>
        </dependency>
    
        <dependency>
          <groupId>org.testng</groupId>
          <artifactId>testng</artifactId>
          <version>${testng.version}</version>
        </dependency>
    
        <dependency>
          <groupId>org.apache.poi</groupId>
          <artifactId>poi</artifactId>
          <version>${poi.version}</version>
        </dependency>
    
        <dependency>
          <groupId>org.apache.poi</groupId>
          <artifactId>poi-ooxml</artifactId>
          <version>${poi.ooxml.version}</version>
        </dependency>
    
        <dependency>
          <groupId>commons-io</groupId>
          <artifactId>commons-io</artifactId>
          <version>${commons.version}</version>
        </dependency>
      </dependencies>
    
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>${maven.compiler.plugin.version}</version>
            <configuration>
              <source>${maven.compiler.source}</source>
              <target>${maven.compiler.target}</target>
            </configuration>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>${maven.surefire.plugin.version}</version>
            <configuration>
              <suiteXmlFiles>
                <suiteXmlFile>testng.xml</suiteXmlFile>
              </suiteXmlFiles>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </project>
    

    package com.example.pages;
    
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.support.PageFactory;
    
    public class BasePage {
        public WebDriver driver;
    
        public BasePage(WebDriver driver) {
            this.driver = driver;
            PageFactory.initElements(driver,this);
        }
    
    }
    

    package com.example.pages;
    
    import com.example.utils.ExcelUtils;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.support.FindBy;
    import org.openqa.selenium.support.PageFactory;
    
    public class LoginPage extends BasePage{
    
        public LoginPage(WebDriver driver) {
            super(driver);
    
        }
    
        @FindBy(name = "username")
        public WebElement userName;
    
        @FindBy(name = "password")
        public WebElement password;
        
        @FindBy(xpath = "//*[@class='oxd-form']/div[1]/div/span")
        public WebElement missingUsernameErrorMessage;
    
        @FindBy(xpath = "//*[@class='oxd-form']/div[2]/div/span")
        public WebElement missingPasswordErrorMessage;
    
        @FindBy(xpath = "//*[@class='oxd-form']/div[3]/button")
        public WebElement login;
    
        @FindBy(xpath = "//*[@id='app']/div[1]/div/div[1]/div/div[2]/div[2]/div/div[1]/div[1]/p")
        public  WebElement errorMessage;
    
    
        public void login(String strUserName, String strPassword) {
    
            userName.sendKeys(strUserName);
            password.sendKeys(strPassword);
            login.click();
    
        }
    
        public String getMissingUsernameText() {
            return missingUsernameErrorMessage.getText();
        }
        
        public String getMissingPasswordText() {
            return missingPasswordErrorMessage.getText();
        }
    
        public String getErrorMessage() {
            return errorMessage.getText();
        }
    
        public LoginPage saveTestResults(int row, int column) {
            ExcelUtils.rowNumber = row ;
            ExcelUtils.columnNumber = column;
            return this;
        }
    
    }
    

    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.support.FindBy;
    import org.openqa.selenium.support.PageFactory;
    
    public class HomePage extends BasePage {
    
        public HomePage(WebDriver driver) {
            super(driver);
    
        }
    
        @FindBy(xpath = "//*[@id='app']/div[1]/div[1]/header/div[1]/div[1]/span/h6")
        public  WebElement homePageUserName;
    
        public String getHomePageText() {
            return homePageUserName.getText();
        }
    
    }
    

    package com.example.utils;
    
    import org.apache.poi.ss.usermodel.DataFormatter;
    import org.apache.poi.xssf.usermodel.XSSFCell;
    import org.apache.poi.xssf.usermodel.XSSFRow;
    import org.apache.poi.xssf.usermodel.XSSFSheet;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    public class ExcelUtils {
    
        public static final String testDataExcelFileName = "testdata.xlsx"; //Global test data excel file
        public static final String currentDir = System.getProperty("user.dir");  //Main Directory of the project
        public static final String resourcePath = "\\src\\test\\resources\\";  //Main Directory of the project
        public static String testDataExcelPath = null; //Location of Test data excel file
        private static XSSFWorkbook excelWorkBook; //Excel WorkBook
        private static XSSFSheet excelWorkSheet; //Excel Sheet
        private static XSSFCell cell; //Excel cell
        private static XSSFRow row; //Excel row
        public static int rowNumber; //Row Number
        public static int columnNumber; //Column Number
        public static FileInputStream ExcelFile;
        public static DataFormatter formatter;
        public static FileOutputStream fileOut;
    
    
        // This method has two parameters: "Test data excel file name" and "Excel sheet name"
        // It creates FileInputStream and set excel file and excel sheet to excelWBook and excelWSheet variables.
        public static void setExcelFileSheet(String sheetName) throws IOException {
    
            testDataExcelPath = currentDir + resourcePath;
    
            // Open the Excel file
            ExcelFile = new FileInputStream(testDataExcelPath + testDataExcelFileName);
            excelWorkBook = new XSSFWorkbook(ExcelFile);
            excelWorkSheet = excelWorkBook.getSheet(sheetName);
    
        }
    
        //This method reads the test data from the Excel cell.
        public static String getCellData(int rowNum, int colNum) {
            cell = excelWorkSheet.getRow(rowNum).getCell(colNum);
            formatter = new DataFormatter();
            return formatter.formatCellValue(cell);
        }
    
        //This method takes row number as a parameter and returns the data of given row number.
        public static XSSFRow getRowData(int rowNum) {
            row = excelWorkSheet.getRow(rowNum);
            return row;
        }
    
        //This method gets excel file, row and column number and set a value to the that cell.
        public static void setCellData(String value, int rowNum, int colNum) throws IOException {
            row = excelWorkSheet.getRow(rowNum);
            cell = row.getCell(colNum);
            if (cell == null) {
                cell = row.createCell(colNum);
                cell.setCellValue(value);
            } else {
                cell.setCellValue(value);
            }
    
            // Write to the workbook
            fileOut = new FileOutputStream(testDataExcelPath + testDataExcelFileName);
            excelWorkBook.write(fileOut);
            fileOut.flush();
            fileOut.close();
        }
    }
    

    import com.example.tests.BaseTests;
    import org.openqa.selenium.WebDriver;
    import org.testng.ITestContext;
    import org.testng.ITestListener;
    import org.testng.ITestResult;
    import java.io.IOException;
    
    public class TestListener implements ITestListener {
    
        private static String getTestMethodName(ITestResult iTestResult) {
            return iTestResult.getMethod().getConstructorOrMethod().getName();
        }
    
        @Override
        public void onStart(ITestContext iTestContext) {
            System.out.println("I am in onStart method :" + iTestContext.getName());
        }
    
        @Override
        public void onFinish(ITestContext iTestContext) {
            System.out.println("I am in onFinish method :" + iTestContext.getName());
        }
    
        @Override
        public void onTestStart(ITestResult iTestResult) {
            System.out.println("I am in onTestStart method :" + getTestMethodName(iTestResult) + ": start");
        }
    
        @Override
        public void onTestSuccess(ITestResult iTestResult)  {
            System.out.println("I am in onTestSuccess method :" + getTestMethodName(iTestResult) + ": succeed");
            try {
                ExcelUtils.setCellData("PASSED", ExcelUtils.rowNumber, ExcelUtils.columnNumber);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    
        @Override
        public void onTestFailure(ITestResult iTestResult)  {
            System.out.println("I am in onTestFailure method :" + getTestMethodName(iTestResult) + " failed");
            try {
                ExcelUtils.setCellData("FAILED", ExcelUtils.rowNumber, ExcelUtils.columnNumber);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    
        @Override
        public void onTestSkipped(ITestResult iTestResult) {
            System.out.println("I am in onTestSkipped method :" + getTestMethodName(iTestResult) + ": skipped");
            try {
                ExcelUtils.setCellData("SKIPPED", ExcelUtils.rowNumber, ExcelUtils.columnNumber);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    
        @Override
        public void onTestFailedButWithinSuccessPercentage(ITestResult iTestResult) {
            System.out.println("Test failed but it is in defined success ratio " + getTestMethodName(iTestResult));
        }
    }
    

    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;
    import org.testng.annotations.AfterMethod;
    import org.testng.annotations.BeforeMethod;
    
    import java.time.Duration;
    
    public class BaseTests {
    
        public static WebDriver driver;
        public final static int TIMEOUT = 10;
    
        @BeforeMethod
        public void setup() {
    
            ChromeOptions options = new ChromeOptions();
            options.addArguments("--remote-allow-origins=*");
            options.addArguments("--no-sandbox");
            options.addArguments("--disable-dev-shm-usage");
            options.addArguments("--headless");
            driver = new ChromeDriver(options);
            driver.manage().window().maximize();
            driver.get("https://opensource-demo.orangehrmlive.com/");
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(TIMEOUT));
    
        }
    
        @AfterMethod
        public void tearDown() {
            driver.quit();
        }
    
    }
    

    package com.example.tests;
    
    import com.example.pages.HomePage;
    import com.example.pages.LoginPage;
    import com.example.utils.ExcelUtils;
    import com.example.utils.TestListener;
    import org.openqa.selenium.WebDriver;
    import org.testng.Assert;
    import org.testng.annotations.BeforeTest;
    import org.testng.annotations.Listeners;
    import org.testng.annotations.Test;
    import java.io.IOException;
    
    @Listeners({TestListener.class })
    public class LoginPageTests extends BaseTests{
    
        String actualResponse;
    
        @BeforeTest
        public void setupTestData() throws IOException {
    
            System.out.println("Setup Test Data");
            ExcelUtils.setExcelFileSheet("LoginData");
        }
    
        @Test
        public void invalidCredentials() throws IOException {
    
            LoginPage objLoginPage = new LoginPage(driver);
            objLoginPage.login(ExcelUtils.getCellData(1,1), ExcelUtils.getCellData(1,2));
            actualResponse = objLoginPage.getErrorMessage();
            ExcelUtils.setCellData(actualResponse,1,4);
            objLoginPage.saveTestResults(1,5);
            Assert.assertEquals(actualResponse,ExcelUtils.getCellData(1,3));
        }
    
        @Test
        public void missingUsername() throws IOException {
    
            LoginPage objLoginPage = new LoginPage(driver);
            objLoginPage.login(ExcelUtils.getCellData(2,1), ExcelUtils.getCellData(2,2));
            actualResponse = objLoginPage.getMissingUsernameText();
            ExcelUtils.setCellData(actualResponse,2,4);
            objLoginPage.saveTestResults(2,5);
            Assert.assertEquals(actualResponse,ExcelUtils.getCellData(2,3));
        }
    
        @Test
        public void missingPassword() throws IOException {
    
            LoginPage objLoginPage = new LoginPage(driver);
            objLoginPage.login(ExcelUtils.getCellData(3,1), ExcelUtils.getCellData(3,2));
            actualResponse = objLoginPage.getMissingPasswordText();
            ExcelUtils.setCellData(actualResponse,3,4);
            objLoginPage.saveTestResults(3,5);
            Assert.assertEquals(actualResponse,ExcelUtils.getCellData(3,3));
        }
    
        //Fail this test
        @Test
        public void validCredentials() throws IOException {
    
            LoginPage objLoginPage = new LoginPage(driver);
            objLoginPage.login(ExcelUtils.getCellData(4,1), ExcelUtils.getCellData(4,2));
            HomePage objHomePage = new HomePage(driver);
            actualResponse = objHomePage.getHomePageText();
            ExcelUtils.setCellData(actualResponse,4,4);
            objLoginPage.saveTestResults(4,5);
            Assert.assertEquals(actualResponse,ExcelUtils.getCellData(4,3));
        }
    
    }
    

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
    <suite name="Data Driven Framework">
        <test name="Login Test">
            <classes>
                <class name="com.example.tests.LoginPageTests"/>
            </classes>
        </test> <!-- Test -->
    </suite> <!-- Suite -->
    

    How to set Proxy in Firefox using Selenium

    HOME

    FirefoxOptions options = new FirefoxOptions();
    
    options.addPreference("network.proxy.type", 1);
    options.addPreference("network.proxy.http", proxyAddress);
    options.addPreference("network.proxy.http_port", proxyPort);
    

    driver = new FirefoxDriver(options);
    

    package org.example;
    
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.firefox.FirefoxOptions;
    
    public class FireFoxProxyDemo {
    
    
        public static void main(String[] args) {
    
            // Set the proxy server details
            String proxyAddress = "localhost";
            int proxyPort = 8080;
            FirefoxDriver driver;
    
            // Create an instance of `FirefoxOptions` and set the proxy configuration
            FirefoxOptions options = new FirefoxOptions();
            options.addPreference("network.proxy.type", 1);
            options.addPreference("network.proxy.http", proxyAddress);
            options.addPreference("network.proxy.http_port", proxyPort);
    
            // Instantiate FireFox Driver with the configured options
             driver = new FirefoxDriver(options);
    
            // Perform your browsing actions using the driver
            driver.get("https://www.google.com");
            System.out.println("Page Title :" + driver.getTitle());
    
            // Close the browser session
            driver.quit();
        }
    }
    

    How to set Proxy in Chrome using Selenium

    HOME

         // Set the proxy server details
            String proxyAddress = "proxy.example";
            int proxyPort = 8080;
    
            // Create a Proxy object and set the HTTP proxy details
            Proxy proxy = new Proxy();
            proxy.setHttpProxy(proxyAddress + ":" + proxyPort);
    

    ChromeOptions options = new ChromeOptions();
    options.setProxy(proxy);
    
    WebDriver driver = new ChromeDriver(options);
    

    import org.openqa.selenium.Proxy;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;
    
    public class ProxyDemo {
    
        public static void main(String[] args) {
    
            // Set the proxy server details
            String proxyAddress = "localhost";
            int proxyPort = 8080;
    
            // Create a Proxy object and set the HTTP proxy details
            Proxy proxy = new Proxy();
            proxy.setHttpProxy(proxyAddress + ":" + proxyPort);
    
            // Configure Chrome options with the Proxy object
            ChromeOptions options = new ChromeOptions();
            options.setProxy(proxy);
            options.addArguments("start-maximized");
    
            // Instantiate ChromeDriver with the configured options
            WebDriver driver = new ChromeDriver(options);
    
    
            // Perform your browsing actions using the driver
            driver.get("https://www.google.com");
            System.out.println("Page Title :" + driver.getTitle());
    
            // Close the browser session
            driver.quit();
        }
    }
    

    CSS Selectors in Selenium Webdriver

    HOME

    (By.cssSelector("input#email"))
    (By.cssSelector("#email"))
    
    • HTML tag – HTML tag of the element being accessed
    • # – The hash sign is use to symbolize ID attribute. It is mandatory to use hash sign if ID attribute is use to create CSS Selector.
    • Value of ID attribute – It is the value of an ID attribute that access. A hash sign always precedes the value of ID.

    If two or more web elements have the same HTML tag and attribute value, the first element marked in the page source will identify.

    2) Located by Class

    Syntax

    (By.cssSelector("input.inputtext"))
    
    • HTML tag = HTML tag of the element being accessed
    • . = the dot sign should always be present when using CSS with class
    • class = class of the element being accessed

    3) Located by Attribute

    (By.cssSelector("input[type='email']"))
    
    • HTML tag = HTML tag of the element being accessed
    • [ and ] = square brackets within which a specific attribute and its corresponding value will be placed
    • attribute = attribute to be used, preferable unique to the element
    • value = corresponding value of the chosen attribute.

    4) Located by  ID/Class and attribute

    (By.cssSelector("input.inputtext[name='email']")
    
    • HTML tag = HTML tag of the element being accessed
    • . = the dot sign should always be present when using a CSS with class
    • class = class of the element being accessed
    • [ and ] = square brackets within which a specific attribute and its corresponding value will be placed
    • attribute = attribute to be used, preferable unique to the element
    • value = corresponding value of the chosen attribute.

    5) Located by Sub String Matches

    CSS in Selenium has an interesting feature of allowing partial string matches using ^$, and *.

    a) Starts with (^): To select the element, we would use ^ which means ‘starts with’.

    (By.cssSelector("input[name^='em']"))
    
    • ^– Symbolic notation to match a string using prefix.

    Prefix – It is the string based on which match operation is performed. The likely string is expected to start with the specified string

    b) Ends with ($): To select the element, we would use $ which means ‘ends with’.

    Syntax

    (By.cssSelector("input[name$='il']"))
    
    • $ – Symbolic notation to match a string using suffix.
    • The suffix – It is the string based on which match operation is perform. The likely string is expect to ends with the specified string.

    c) Contains (*): To select the element, we would use * which means ‘sub-string’.

    Syntax

    (By.cssSelector("input[name*='rst']"))
     
    (By.cssSelector("input:contains('rst')")
    

    – This is used to match the sub-string

    6) Locating child element

    Here, id =”content” is the parent locator. It will go to first div as child or sub child, then again div as child or sub child, and third div as child or sub child. Then it will go to div class _4bl7 _m-_ which further go to div class _ihd _3ma mbs _6n _6s _6v.

    Syntax

    (By.cssSelector("#content>div>div>div>div._4bl7._m-_>div._ihd._3ma.mbs._6n._6s._6v"))
    

    Locating nth Child:

    To locate the element with text ‘Female’, we use nth type css.

    Syntax

    (By.cssSelector("#u_0_13 > span:nth-child(1) > label"))
    

    To select the last child element, i.e. ‘Male’, we can use.

    Syntax

    (By.cssSelector("#u_0_13 > span:last-child> label"))
    

    Now, let’s write a small program to show the use of CSS Selectors. This program is it we have done for XPath , the only difference is the use of CSS Selectors to identify the web elements.

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;
    import java.time.Duration;
    
    public class Selenium_Demo {
    
        protected static WebDriver driver;
    
        public static void main(String[] args) {
    
            ChromeOptions options = new ChromeOptions();
            options.addArguments("--start-maximized");
            driver = new ChromeDriver(options);
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(2));
            driver.get("https://opensource-demo.orangehrmlive.com/");
            driver.manage().window().maximize();
    
            //CSS Selectors for TextBox
            driver.findElement(By.cssSelector("input.oxd-input[name='username'")).sendKeys("Admin");
    
            driver.findElement(By.cssSelector("input.oxd-input[name='password'")).sendKeys("admin123");
    
            driver.findElement(By.cssSelector("button[type='submit'")).click();
            
            driver.close();
        }
    }
    

    isDisplayed, isSelected, isEnabled in Selenium

    HOME

    This tutorial describes how to check the state of a WebElement in Selenium.

    In this tutorial, we will learn the isDisplayed, isEnabled, isSelected method in Selenium, and how to check the state of a WebElement. There are many methods that are used to determine the visibility scope for the web elements – isSelected(), isEnabled(), and isDispalyed().

    Many a time, a test fails when we click on an element or enter text in a field. This is because the element is displayed or exists in DOM, but it does not exist on the web page.

    WebDriver facilitates the user with the following methods to check the visibility of the web elements. These web elements can be buttons, drop boxes, checkboxes, radio buttons, labels, etc.

    • isDisplayed()
    • isSelected()
    • isEnabled()

    1) Boolean isSelected(): This method determines if an element is selected or not. It returns true if the element is selected and false if it is not. It is widely used on checkboxes, radio buttons, and options in a select.

    2) Boolean isDisplayed(): This method determines if an element is displayed or not. It returns true if the element is displayed and false if it is not. The advantage of this method is that it avoids parsing an element’s style attribute.

    3) Boolean isEnabled(): This method determines if an element is enabled or not. It returns true if the element is enabled (All elements apart from disabled input elements) and false if otherwise.

    Steps to follow to understand when an element isEnabled and isDisplayed.

    1. Launch the web browser and open the application under test – https://duckduckgo.com/
    2. Verify the web page title
    3. Verify if the “Search Box” is displayed
    4. Verify that the “Search Box” is enabled
    5. If Search Box is enabled, then search for text – Selenium
    6. Close the browser

    The complete program is shown below:

    package org.example;
    
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.firefox.FirefoxOptions;
    
    import java.util.concurrent.TimeUnit;
    
    public class VerifyConditionsDemo {
    
        public static void main(String[] args) {
    
            // Initiate Firefox browser
            FirefoxOptions options = new FirefoxOptions();
            WebDriver driver = new FirefoxDriver(options);
    
            // Maximize the browser
            driver.manage().window().maximize();
            driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    
            // launch the firefox browser and open the application url
            driver.get("https://duckduckgo.com/");
    
            // compare the expected title of the page with the actual title of the page and
            String expectedTitle = "DuckDuckGo — Privacy, simplified.";
            String actualTitle = driver.getTitle();
            if (expectedTitle.equals(actualTitle)) {
                System.out.println("Verification Pass- The correct title is displayed on the web page.");
            } else {
                System.out.println("Verification Failed - An incorrect title is displayed on the web page.");
            }
    
            // Verify that the “Search" Box is displayed
            WebElement searchBox = driver.findElement(By.className("searchbox_input__bEGm3"));
            if (searchBox.isDisplayed()) {
                System.out.println("Search Box is visible. Return: " + searchBox.isDisplayed());
            } else {
                System.out.println("Search Box is not visible. Return: " + searchBox.isDisplayed());
            }
    
            // Verify that the “Search” Box is enabled
            if (searchBox.isEnabled()) {
                System.out.println("Search Box is enabled. Return: " + searchBox.isEnabled());
                searchBox.sendKeys("Selenium");
            } else {
                System.out.println("Search Box is not enabled. Return: " + searchBox.isEnabled());
            }
    
            System.out.println("Successful Execution of Test.");
    
            // close the web browser
            driver.close();
    
        }
    }
    

    The output of the above program is

    isSelected

    Steps to follow to understand when an element is Selected or not

    1. Launch the web browser and open the application under test – https://demoqa.com/radio-button
    2. Print all the options for the Radio Button
    3. Verify if the first Radio Button (Yes) is selected or not
    4. If the first radio button is not selected, then select Radio Button 1, else select button 2.
    5. Print the value of the selected Radio Button
    6. Close the browser

    Below is the image of the options for the Radio Button.

    The complete program is shown below:

    package org.example;
    
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.firefox.FirefoxOptions;
    
    import java.util.List;
    import java.util.concurrent.TimeUnit;
    
    public class isSelectedDemo {
    
            public static void main(String[] args) {
    
    
                // Initiate Firefox browser
                FirefoxOptions firefoxOptions = new FirefoxOptions();
                WebDriver driver = new FirefoxDriver(firefoxOptions);
    
                // Maximize the browser
                driver.manage().window().maximize();
                driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    
                driver.get("https://demoqa.com/radio-button");
    
                List<WebElement> Radio_Options = driver.findElements(By.cssSelector(".custom-radio"));
                for(WebElement options: Radio_Options)
                    System.out.println("Options :"+ options.getText());
    
                // Create a boolean variable which will hold the value (True/False)
                boolean radio_value = false;
    
                // This statement will return True, in case of first Radio button is already selected
                radio_value = Radio_Options.get(0).isSelected();
                System.out.println("First Option is already selected :"+radio_value);
    
                // If button 1 is not selected, then select otherwise select button 2
                if (radio_value == false) {
                    Radio_Options.get(0).click();
                    System.out.println("Button Selected is :" + Radio_Options.get(0).getText());
                } else {
                    Radio_Options.get(1).click();
                    System.out.println("Button Selected is :" + Radio_Options.get(1).getText());
                }
    
                // close the web browser
                driver.close();
            }
        }
    

    The output of the above program is

    That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!