Selenium Introduction

  1. Selenium is a free (open source) automated testing suite for web applications across different browsers, platforms and programming languages.
  2. Selenium can be easily deployed on platforms such as Windows, Linux, Solaris and Macintosh. Moreover, it supports for mobile applications like iOS and android.
  3. Languages supported by Selenium include C#, Java, Perl, PHP, Python and Ruby.
  4. Browsers supported by Selenium include Internet Explorer, Mozilla Firefox, Google Chrome and Safari.
  5. Automation testing covers both functional and performance test on an application.

Selenium Features

  1. Selenium is a free (open source) automated testing suite for web applications across different browsers, platforms and programming languages.
  2. Selenium IDE provides a playback and record feature for authoring tests without the need to learn a test scripting language.
  3. It helps testers to record their actions and export them as a reusable script with a simple-to-understand and easy-to-use interface.
  4. It also supports parallel test execution which reduces time and increases the efficiency of tests.
  5. Selenium can be integrated with frameworks like Ant and Maven for source code compilation, and can be integrated with testing frameworks like TestNG for application testing and generating reports.
  6. Selenium requires fewer resources as compared to other automation test tools.
  7. Selenium web driver does not require server installation, test scripts interact directly with the browser.

Selenium Limitations

  1. Selenium does not support automation testing for desktop applications.
  2. Selenium requires high skill sets in order to automate tests more effectively.
  3. Since Selenium is open source software, you have to rely on community forums to get your technical issues resolved.
  4. We should know at least one of the supported programming languages to create tests scripts in Selenium WebDriver.
  5. Selenium does not have any inbuilt reportingcapability; you have to rely on plug-ins like JUnit and TestNG for test reports.
  6. It is not possible to perform testing on images.
  7. No one is responsible for new features usage; they may or may not work properly.


Selenium Tool Suite

  1. Selenium is not just a single tool but a suite of software's, each catering to different testing needs of an organization. It has four components.
    • Selenium Integrated Development Environment (IDE)
    • Selenium Remote Control (RC) [Now Deprecated]
    • WebDriver
    • Selenium Grid

Selenium IDE

  1. Selenium Integrated Development Environment (IDE) is the simplest framework in the Selenium suite and is the easiest one to learn.
  2. It is a Firefox/Chrome plugin that you can install as easily as you can with other plugins.
  3. However, because of its simplicity, Selenium IDE should only be used as a prototyping tool.
  4. Selenium IDE is implemented as Firefox extension which provides record and playback functionality on test scripts.
  5. It allows testers to export recorded scripts in many languages like HTML, Java, Ruby, RSpec, Python, C#, JUnit and TestNG. You can use these exported script in Selenium RC or Webdriver.

Selenium IDE-Installation

  1. Open Selenium official website seleniumhq.org
  2. Then click on Download Section.
  3. In the webpage search for Selenium IDE and click on Chrome to install Google Chrome plug-in or click on Firefox to install Firefox Plug-in.
  4. Restart you browser, go to the top right corner on your browser and look for the Selenium IDE icon.
  5. Click on that icon to launch Selenium IDE.

Selenium IDE-Features

  1. Very easy to use and install.
  2. No programming experience is requied.
  3. Export tests to different programming languages.

Selenium IDE-Limitations

  1. Available in only Firefox and Chrome.
  2. Designed only to create prototypes of tests.
  3. Test execution is slow.

Selenium Webdriver

  1. Selenium WebDriver is the most important component of Selenium Tool's Suite.
  2. The initial version of Selenium i.e Selenium v1 consisted of only IDE, RC and Grid. Selenium WebDriver was first introduced as a part of Selenium v2.0. However, with the release of Selenium v3, RC has been deprecated and moved to legacy package.
  3. In WebDriver, test scripts can be developed using any of the supported programming languages and can be run directly in most modern web browsers. Languages supported by WebDriver include C#, Java, Perl, PHP, Python and Ruby.
  4. Selenium Web driver is most popular with Java and C#.
  5. Selenium WebDriver performs much faster as compared to Selenium RC because it makes direct calls to the web browsers. RC on the other hand needs an RC server to interact with the browser.
  6. Selenium uses drivers, specific to each browser in order to establish a secure connection with the browser without revealing the internal logic of browser's functionality.
  7. WebDriver is supporting dynamic web pages where elements of a page may change without the page itself being reloaded.
  8. The more pain while doing automation is the handling Javascripts alerts & prompts. The WebDriver very verse with handle the Javascript alerts, prompts and handling multiple frames, multiple browser windows.

Selenium WebDriver- Features

Selenium WebDriver- Installation



Selenium WebDriver- First TestCase

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class BrowserDemo {

    public static void main(String[] args) {

        //InternetExplorer
        System.setProperty("webdriver.ie.driver", "E:\\Softwares\\IEDriverServer.exe");
        WebDriver driver = new InternetExplorerDriver();
        driver.manage().window().maximize();
        driver.get("http://google.com");
        System.out.println(driver.getTitle());
        System.out.println(driver.getCurrentUrl());

        //GoogleChrome
        System.setProperty("webdriver.chrome.driver", "E:\\Softwares\\ChromeDriver.exe");
        WebDriver driver2 = new ChromeDriver();
        driver2.manage().window().maximize();
        driver2.get("http://google.com");
        System.out.println(driver2.getTitle());
        System.out.println(driver2.getCurrentUrl());

        //Firefox
        System.setProperty("webdriver.gecko.driver", "E:\\Softwares\\geckodriver.exe");
        WebDriver driver3 = new InternetExplorerDriver();
        driver.manage().window().maximize();
        driver3.get("http://google.com");
        System.out.println(driver3.getTitle());
        System.out.println(driver3.getCurrentUrl());
    }
}
  1. In selenium, we use System.setProperty("name","value") method because the browser doesn’t have a built-in server to run the automation code so you will need a Chrome/IE/Gecko(according to requirement) driver server for communicating your Selenium code to the browser. In this method we have to pass two parameters, first parameter is name of the browser which we want to connect and second parameter is the path of the related driver which we have downloaded in Step 3.
    For example System.setProperty("webdriver.ie.driver", "E:\\Softwares\\SeleniumDrivers\\IEDriverServer.exe");
  2. In the next step we have created a browser object to access and to perform some operations on that browser. WebDriver defines common methods which all browser classes (such as Firefox, Chrome etc.,) use. All these class methods are derived from WebDriver interface.
    For example WebDriver driver = new InternetExplorerDriver();
  3. The WebDriver provides the window interface for setting up the browser window size, state, and so on. When we call the maximize() method, the browser window will be maximized from normal or minimized state.
    For example driver.manage().window().maximize();
  4. If we want to open a specific URL on that browser we will use get() method. In that method we have to pass the specific URL.
    For example driver.get("http://google.com");
  5. If we want to get current page title we wil use driver.gettitle() method and if we want to get current page URL we will use driver.getCurrentUrl() method.


Locating Web Elements

  1. By Id: Locates element using id attribute of the web element.
  2. WebElement element = driver.findElement(By.id("elementId"));
  3. By className: Locates the web element using className attribute.
  4. WebElement element = driver.findElement(By.className("elementsClass"));
  5. By tagName: Locates the web element using its html tag like div, a, input etc.
  6. WebElement element = driver.findElement(By.tagName("a"));
  7. By name: Locates the web element using name attribute.
  8. WebElement element = driver.findElement(By.name("male"));
  9. By linkText: Locates the web element of link type using their text.
  10. WebElement element = driver.findElement(By.linkText("Click Here"));
  11. By partialLinkText: Locates the web element of link type with partial matching of text.
  12. WebElement element = driver.findElement(By.partialLinkText("Click"));
  13. By cssSelector: Locates the web element using css its CSS Selector patterns
  14. WebElement element = driver.findElement(By.cssSelector("div#elementId"));
  15. By xpath: Locates the web element using its XPaths
  16. WebElement element = driver.findElement(By.xpath("//div[@id=’elementId’]"));
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

class LocatorsDemo {
    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("http://fb.com");

        driver.findElement(By.id("email")).sendKeys("9052938526");
        driver.findElement(By.name("pass")).sendKeys("password");
        driver.findElement(By.className("inputtext")).sendKeys("abhishek@gmail.com");
        driver.findElement(By.tagName("input")).sendKeys("7569645388");
        driver.findElement(By.partialLinkText("Forgotten")).click();
        driver.findElement(By.linkText("Forgotten Password?")).click();
        driver.findElement(By.cssSelector("#u_0_q")).sendKeys("9052938526");
        driver.findElement(By.xpath("//*[@id=\"reg_pages_msg\"]/a")).click();
    }
}

Selenium WebDriver Commands

  1. Here we will learn some of the basic selenium commands for performing operations like opening a URL, clicking on buttons, writing in textbox, closing the browser etc.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

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

        System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();

        driver.get("file:///C:/Users/user/Desktop/Selenium.html");
         System.out.println(driver.getTitle());
         System.out.println(driver.getCurrentUrl());
         driver.findElement(By.xpath("xpath1"));
         driver.close();
         driver.quit();
         driver.navigate().to("https://google.com");
         Thread.sleep(10000);
         driver.navigate().back();
         Thread.sleep(5000);
         driver.navigate().forward();
         driver.navigate().refresh();
         driver.findElement(By.xpath("hello")).sendKeys("9052938526");
         Thread.sleep(5000);
         driver.findElement(By.xpath("hello")).clear();
         System.out.println(driver.findElement(By.id("heading2")).getText());
         System.out.println(driver.findElement(By.id("selenium")).isDisplayed());
         System.out.println(driver.findElement(By.id("b2")).isEnabled());
        System.out.println(driver.findElement(By.id("male")).isSelected());
  }

}
        


Handling Textboxes in Selenium

  1. Basically a textbox is an input tag and will accept character sequence.
  2. Input boxes refer to either of these two types:
    • Text Fields- text boxes that accept typed values and show them as they are.
    • Password Fields- text boxes that accept typed values but mask them as a series of special characters (commonly dots and asterisks) to avoid sensitive values to be displayed.
  3. We need to use sendKeys() method to enter data into textbox after identifying the webelement on the webpage.
  4. driver.findElement(By.id("name")).sendKeys("Abhishek");
  5. To clear the textbox we can use clear() method of selenium.
  6. driver.findElement(By.id("name")).clear();
  7. We can retrieve value which we have typed or already typed in text box. It will be useful when we want to verify if correct value is typed or to know existing value in text box. To retrieve value from text box, we need to use getAttribute("value") method.
  8. driver.findElement(By.id("name")).getAttribute("value");
  9. We can also get the type of the text box. For this purpose we use getAttribute("type") method.
  10. driver.findElement(By.id("name")).getAttribute("type");
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

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

    	System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();

        driver.get("file:///C:/Users/user/Desktop/Selenium.html");
        WebElement name = driver.findElement(By.id("name"));
        name.sendKeys("Kotha Abhishek");
        driver.findElement(By.id("pwd")).sendKeys("Abhishek");
        name.clear();
        System.out.println(name.getAttribute("value"));
        System.out.println(name.getAttribute("type"));

    }

}
        

Handling Alerts / PopUps in Selenium

  1. Alert is a small message box which displays on-screen notification to give the user some kind of information or ask for permission to perform certain kind of operation. It may be also used for warning purpose.
  2. Selenium WebDriver provides three methods to accept and reject the Alert depending on the Alert types.
  3. We need to use accept() to click on the 'Ok' button of the alert.
  4. driver.switchTo().alert().accept();
  5. We can use dismiss() to click on the 'Cancel' button of the alert.
  6. driver.switchTo().alert().dismiss();
  7. We need to use getText() to capture the alert message.
  8. driver.switchTo().alert().getText();
  9. We can use sendKeys("Text") to send some data to the alert box.
  10. driver.switchTo().alert().sendKeys("Text");
        import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

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

    	System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();

        driver.get("file:///C:/Users/user/Desktop/Selenium.html");
          driver.findElement(By.id("file")).click();
          driver.findElement(By.id("file")).sendKeys("C:\\Users\\user\\Desktop\\Selenium.html");
          Thread.sleep(3000);
          driver.switchTo().alert().accept();
          driver.switchTo().alert().dismiss();
          System.out.println(driver.switchTo().alert().getText());
          driver.switchTo().alert().sendKeys("9052938526");
          driver.switchTo().alert().accept();

          Alert alertbox = driver.switchTo().alert();
          alertbox.sendKeys("9052938526");
          alertbox.accept();

    }

}

Handling Dropdown in Selenium

  1. The 'Select' class in Selenium WebDriver is used for selecting an option in a dropdown. The objects of Select type can be initialized by passing the dropdown webElement as parameter to its constructor.
  2. To perform any action, the first task is to identify the element group. I am saying it a group, as DropDown /Multiple Select is not a single element. They always have a single name but and they contain one or more than one element in them.
  3. Select dropdown = new Select(driver.findElement(By.name("country")));
  4. WebDriver provides three ways to select an option from the drop-down menu.
  5. We can use selectByIndex() to select an option based on its index, beginning with 0.
  6. dropdown.selectByIndex(5);
  7. We need to use selectByValue() to select an option based on its 'value' attribute.
  8. dropdown.selectByValue("India");
  9. We can use selectByVisibleText() to select an option based on the text over the option.
  10. dropdown.selectByVisibleText("Database Testing");
  11. We can use getOptions( ) to get the all options belonging to the Select tag. It takes no parameter and returns List<WebElements>.
  12. List <WebElement> options = dropdown.getOptions();
    int size=options.size();
    System.out.println(size);
    for(int i =0; i<size ; i++){
    String optValue = options.get(i).getText();
    System.out.println(optValue);
    }
import java.util.List;
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.support.ui.Select;


class Selenium {
    public static void main(String[] args) {

      System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();

        driver.get("file:///C:/Users/user/Desktop/Selenium.html");
        Select dropdown1 = new Select(driver.findElement(By.name("country")));
        dropdown1.selectByVisibleText("India");
        dropdown1.selectByIndex(5);
        dropdown1.selectByValue("Australia");
        List<WebElement> list1 = dropdown1.getOptions();
        int size=list1.size();
        System.out.println(size);
        for(int i =0; i<size ; i++){
          String optValue = list1.get(i).getText();
          System.out.println(optValue);
        }
    }
}

Handling Tables in Selenium

  1. There are two types of HTML tables published on the web.
    • Static tables : Data is static i.e. Number of rows and columns are fixed.
    • Dynamic tables : Data is dynamic i.e. Number of rows and columns are NOT fixed.
  2. Handling static table is easy, but dynamic table is a little bit difficult as rows and columns are not constant.
  3. Below tags are generally defined in html tables :
    • ’table’ tag defines HTML table.
    • ’tbody’ tag defines a container for rows and columns.
    • ’tr’ defines rows in an HTML table.
    • ’td’/’th’ define the column of an HTML table.
  4. First get the entire HTML table and store this in a variable of type web element.
  5. WebElement htmltable=driver.findElement(By.xpath("//*[@id='main']/table[1]/tbody"));
  6. Get all the rows with tag name ‘tr’ and store all the elements in a list of web elements. Now all the elements with tag ‘tr’ are stored in ‘rows’ list.
  7. List<WebElement> rows=htmltable.findElements(By.tagName("tr"));
  8. Loop through each row and get the list of elements with tag ‘th’.
  9. List<WebElement> columns=rows.get(rnum).findElements(By.tagName("th")); System.out.println("Number of columns:"+columns.size());
  10. Iterate using ‘columns.getsize()’ and get the details of each cell.
  11. System.out.println(columns.get(cnum).getText());
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;


class Selenium {
    public static void main(String[] args) {

      System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();

        driver.get("file:///C:/Users/user/Desktop/Selenium.html");
        WebElement table = driver.findElement(By.xpath("/html/body/table"));
        List <WebElement> rows = table.findElements(By.xpath("/html/body/table/tbody/tr"));
        int rowcount = rows.size();

        List <WebElement> columns = table.findElements(By.xpath("/html/body/table/tbody/tr[1]/th"));
        int columncount = columns.size();

        List <WebElement> cells = table.findElements(By.xpath("/html/body/table/tbody/tr/th"));
        System.out.println(cells.size());

        for(int i=1; i<=1; i++){
          for(int j=1; j<=columncount; j++) {
            System.out.print(table.findElement(By.xpath("/html/body/table/tbody/tr["+i+"]/th["+j+"]")).getText()+" ");
          }
          System.out.println();
        }
        for(int i=2; i<=rowcount; i++){
          for(int j=1; j<=columncount; j++) {
            System.out.print(table.findElement(By.xpath("/html/body/table/tbody/tr["+i+"]/td["+j+"]")).getText()+" ");
          }
          System.out.println();
        }
    }
}
        

Handling iFrames in Selenium

  1. IFrame is a web page which is embedded in another web page or an HTML document embedded inside another HTML document.
  2. The IFrame is often used to insert content from another source, such as an advertisement, into a Web page.
  3. We cannot detect the frames by just seeing the page or by inspecting.
  4. We can identify the iframes using methods given below:
    • Right click on the element, If you find the option like 'This Frame', 'view Frame source' or ''Reload Frame' then it is an iframe.
    • Right click on the page and click 'View Page Source' and Search with the 'iframe', if you can find any tag name with the 'iframe' then it is meaning to say the page consisting an iframe.
  5. We can even identify total number of iframes by using below snippet.
  6. int size = driver.findElements(By.tagName("iframe")).size();
  7. Basically, we can switch over the elements in frames using 2 ways.
  8. Switch to the frame by index : Index is one of the attributes for the Iframe through which we can switch to it. Index of the iframe starts with '0'.
  9. driver.switchTo().frame(0);
  10. Switch to the frame by Name or ID : Name and ID are attributes of iframe through which we can switch to the frame.
  11. driver.switchTo().frame("iframe1");
  12. Switch back to the Main Frame : To move back to the parent frame, you can either use switchTo().parentFrame() or if you want to get back to the main (or most parent) frame, you can use switchTo().defaultContent();
  13. driver.switchTo().parentFrame();
    driver.switchTo().defaultContent();
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

class Selenium {
    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();

        driver.get("file:///C:/Users/user/Desktop/Selenium.html");
        driver.switchTo().frame("seleniumframe");
        String heading = driver.findElement(By.xpath("//*[@id=\"1\"]")).getText();
        System.out.println(heading);

        driver.switchTo().parentFrame();

        driver.switchTo().frame(1);
        String heading2 = driver.findElement(By.xpath("//*[@id=\"1\"]")).getText();
        System.out.println(heading2);

        int framecount = driver.findElements(By.tagName("iframe")).size();
        System.out.println(framecount);

    }
}
        

Selenium Headless Browser Testing

  1. A headless browser is a web-browser without a graphical user interface. This program will behave just like a browser but will not show any GUI.
  2. Improves speed and performance.
  3. Helps you multitask.
  4. Some of the examples of Headless Drivers include :
    • HtmlUnit
    • Chrome
    • Firefox
  5. HTMLUnitDriver : HTML UnitDriver is the most light weight and fastest implementation headless browser for of WebDriver. It is based on HtmlUnit. It is known as Headless Browser Driver. It is same as Chrome, IE, or FireFox driver, but it does not have GUI so one cannot see the test execution on screen.
    • Support for the HTTPS and HTTP protocols
    • Support for HTML responses ( clicking links, submitting forms, walking the DOM model of the HTML document etc.)
    • Support for cookies
    • Excellent JavaScript support
    • Support for submit methods GET and POST

    WebDriver driver = new HtmlUnitDriver();

    We have to download 2 jar files ( htmlunit-driver-2.41.0-jar-with-dependencies.jar , htmlunit-driver-2.41.0.jar ) for HtmlUnit Driver and we have to bind them with our project to use HtmlUnitDriver. Click here to download files
  6. Chrome Driver : Chrome provides a headless mode, which works well overall. The biggest downside is that you need to be able to install Chrome. You don’t need a UI, but installing software is not always possible.
  7. ChromeOptions options = new ChromeOptions();
    options.addArguments("--headless");
    (or)
    options.setHeadless(true);
    WebDriver driver = new ChromeDriver(options);

  8. Gecko Driver : Firefox also has a headless mode. which works just like the Chrome one. You download the Gecko Driver and use selenium-firefox-driver.
  9. FirefoxBinary firefoxBinary = new FirefoxBinary();
    firefoxBinary.addCommandLineOptions("--headless");
    FirefoxOptions options = new FirefoxOptions();
    options.setBinary(firefoxBinary);
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

class Selenium {
    public static void main(String[] args) {

      System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\chromedriver.exe");
      ChromeOptions options = new ChromeOptions();
      options.addArguments("headless");
      // options.setHeadless(true);
      WebDriver driver = new ChromeDriver(options);

      WebDriver driver = new HtmlUnitDriver();

      FirefoxBinary firefoxBinary = new FirefoxBinary();
      firefoxBinary.addCommandLineOptions("--headless");
      FirefoxOptions options = new FirefoxOptions();
      options.setBinary(firefoxBinary);
      WebDriver driver = new FirefoxDriver(options);

        driver.get("file:///C:/Users/user/Desktop/Selenium.html");

        System.out.println(driver.getCurrentUrl());
        System.out.println(driver.getTitle());

    }
}
        

Verify If Options In Dropdown Are Sorted or Not?

  1. Open the browser and navigate to the webpage.
  2. Find the dropdown using the findElement method in selenium. Create a object to Select class and pass the dropdown element as the parameter to constructor.
  3. Using getOptions() method from Select class you can get all the options from the dropdown in the form of WebElement. Using the loop we can retrive the values from the List of WebElement.
  4. Now lets create a temporary list called tempList and get the values from originalList. Now sort the Either tempList or originalList and compare them, We can sort the list using the Collections.sort(list) method.
  5. We can compare the list using conditional statement.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

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.support.ui.Select;


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

    System.setProperty("webdriver.chrome.driver","E:\\Drivers\\chromedriver.exe");
    WebDriver driver= new ChromeDriver();

    driver.get("file:///C:/Users/user/Desktop/Selenium.html");

    WebElement carslist = driver.findElement(By.id("cars"));
    Select dropdown = new Select(carslist);

    List<WebElement> allOptions = dropdown.getOptions();

    List options = new ArrayList();

    for(WebElement optionElement : allOptions){
      options.add(optionElement.getText());
    }

    System.out.println("Options in dropdown with Default order :"+options);

    List tempList = new ArrayList<>(options);

    Collections.sort(tempList);

    System.out.println("Sorted List "+ tempList);

    boolean ifSortedAscending = options.equals(tempList);

    if(ifSortedAscending)
    {
      System.out.println("List is sorted");
    }
    else
      System.out.println("List is not sorted.");


    driver.quit();

  }
}
        

Handle Multiple Windows/Tabs in Selenium

  1. On an HTML page, a link can open up in a new window/tab.
  2. There is only one way you can get multiple windows via Selenium web driver, that is by clicking on a link that opens the page in a new browser window.
  3. Selenium web driver keeps a track of how many windows it opened during a session.
  4. Window handle is a unique string value that uniquely identifies a Browser window on desktop. It is guaranteed that each browser will have a unique window handle.
  5. To get Window handle WebDriver interface provides two methods – getWindowHandle(), getWindowHandles().
  6. getWindowHandle() : method return a string value and it returns the Window handle of current focused browser window.
  7. getWindowHandles() : method returns a set of all Window handles of all the browsers that were opened in the session.
  8. There is a concept of current focused window which means that all selenium webdriver commands will go to the focused window. By default the focus is always on the Parent window.
  9. WebDriver.SwitchTo().window(String windowHandle) : This command takes in a window handle and switches the driver context on that window. Once the Switch happens all the driver commands will go to the newly focused window. This is very important to understand, without switching to the desired window we wil not be able to perform any action on that window.
  10. WebDriver.Close() : command will close the current window on which the focus is present. This can be used to close windows selectively. Just switch to the window that you want to close by using the correct Window handle and the call the WebDriver.close command.
  11. WebDriver.quit() : command will close all the windows opened in the session. This command basically shuts down the driver instance and any further commands to WebDriver results in exception.
import java.util.Iterator;
import java.util.Set;

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

class Selenium {
    public static void main(String[] args) {

      System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().window().maximize();

        driver.get("file:///C:/Users/user/Desktop/Selenium.html");

        driver.findElement(By.xpath("//*[@id=\'c\']")).click();
        driver.findElement(By.xpath("//*[@id=\'java\']")).click();
        driver.findElement(By.xpath("//*[@id=\'python\']")).click();

        Set<String> windows = driver.getWindowHandles();
        int size = windows.size();
        System.out.println(windows);
        String ids[] = new String[size];

        Iterator<String> itr = windows.iterator();

        for(int i=0; i<size; i++) {
          ids[i] = itr.next();
        }

        System.out.println("Parent window Title : "+driver.getTitle());

        driver.switchTo().window(ids[2]);
        System.out.println("2nd Child window Title : "+driver.getTitle());

        driver.switchTo().window(ids[3]);
        System.out.println("3rd Child window Title : "+driver.getTitle());

        driver.switchTo().window(ids[1]);
        System.out.println("1st Child window Title : "+driver.getTitle());

        driver.switchTo().window(ids[0]);
        System.out.println("Parent window Title : "+driver.getTitle());
        driver.quit();

    }
}

        

Mouse Click & Keyboard Event: Actions Class

  1. Actions class is an ability provided by Selenium for handling keyboard and mouse events.
  2. In Selenium WebDriver, handling these events includes operations such as drag and drop, clicking on multiple elements with the control key.
  3. The following are the most commonly used keyboard and mouse events provided by the Actions class.
  4. clickAndHold() : Clicks (without releasing) at the current mouse location.
  5. contextClick() : Performs a context-click at the current mouse locationPerforms a key release.. (Right Click Mouse Action).
  6. doubleClick() : Performs a double-click at the current mouse location.
  7. dragAndDrop(source, target) : Performs click-and-hold at the location of the source element, moves to the location of the target element, then releases the mouse.
  8. keyDown(modifier_key) : Performs a modifier key press. Does not release the modifier key - subsequent interactions may assume it's kept pressed. (Keys.ALT, Keys.SHIFT, or Keys.CONTROL).
  9. keyUp(modifier _key) : Performs a key release.
  10. moveToElement(toElement) : Moves the mouse to the middle of the element.
  11. release() : Releases the depressed left mouse button at the current mouse location.
  12. Instantiate a new Actions object.
  13. Actions action = new Actions(driver);
  14. Use the perform() method when executing the Action object
  15. You can build a series of actions using the Action and Actions classes. Just remember to close the series with the build() method.
  16. Build().perform() is used to compile and execute the actions class.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

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

      System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().window().maximize();

        driver.get("file:///C:/Users/user/Desktop/Selenium.html");

        Actions act = new Actions(driver);

        WebElement source =  driver.findElement(By.xpath("//*[@id=\'box6\']"));
        WebElement destination = driver.findElement(By.xpath("//*[@id=\'box106\']"));
        WebElement element3 = driver.findElement(By.xpath("//*[@id=\'header\']/nav/div/div[2]/ul/li[6]/ul/li[1]/ul/li[2]/a"));

        act.moveToElement(element1).build().perform();
        act.moveToElement(element2).build().perform();
        act.moveToElement(element3).click().build().perform();

        act.moveToElement(element1).moveToElement(element2).moveToElement(element3).click().build().perform();

        act.clickAndHold(source).moveToElement(destination).release().build().perform();

        WebElement source2 =  driver.findElement(By.xpath("//*[@id=\'box1\']"));
        WebElement destination2 = driver.findElement(By.xpath("//*[@id=\'box101\']"));

        act.dragAndDrop(source, destination).build().perform();
        act.clickAndHold(source2).moveToElement(destination2).release().build().perform();

        Thread.sleep(5000);
        WebElement button = driver.findElement(By.xpath("/html/body/div/section/div/div/div/p/span"));

        act.contextClick(button).build().perform();
        act.moveToElement(driver.findElement(By.xpath("/html/body/ul/li[5]/span"))).click().build().perform();

        WebElement name = driver.findElement(By.id("name"));
        act.keyDown(name, Keys.SHIFT).sendKeys("abhishek").build().perform();

    }
}

        

How to Find All Broken links using Selenium

  1. Broken links are links or URLs that are not reachable. They may be down or not functioning due to some server error.
  2. You should always make sure that there are no broken links on the site because the user should not land into an error page.
  3. Manual checking of links is a tedious task, because each webpage may have a large number of links & manual process has to be repeated for all pages.
  4. Collect all the links in the web page based on <a> tag.
  5. Send HTTP request for the link and read HTTP response code.
  6. Find out whether the link is valid or broken based on HTTP response code.
  7. Repeat this for all the links captured.
  8. There are different HTTP status codes which are having different purposes.
  9. An URL will always have a status with 2xx which is valid.
  10. For an invalid request, HTTP status is 4xx and 5xx.
  11. 4xx class of status code is mainly for client side error, and 5xx class of status codes is mainly for the server response error.
  12. We will most likely be unable to confirm if that link is working or not until we click and confirm it.
  13. Identify all links in a webpage and store them in List.
  14. List<WebElement> links = driver.findElements(By.tagName("a"));
  15. Obtain Iterator to traverse through the List.
  16. Iterator it = links.iterator();
  17. Now the most important part is to check in the links are working. Here I will introduce to you a Class from Java, called HttpURLConnection class. This class is used to make HTTP requests to the webserver hosting the links extracted
  18. Consider an air ticket booking application. The color of booked and available seats are different. Red represents the booked seats, and available seats are represented by green. So, for verifying whether a seat is booked or available, QAs need to fetch the attribute (color) value through the test script. Once the status of the seat is verified, only then can QAs verify further test scenarios.
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

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

class Selenium {
    public static void main(String[] args) throws InterruptedException, IOException {

      System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().window().maximize();

        driver.get("http://newtours.demoaut.com/");

        List<WebElement> links = driver.findElements(By.tagName("a"));

        System.out.println(links.size());

        for(int i=0; i<links.size(); i++) {
          WebElement element = links.get(i);
          String url = element.getAttribute("href");

          URL link=new URL(url);

          HttpURLConnection httpcon = (HttpURLConnection) link.openConnection();
          httpcon.connect();

          int rescode = httpcon.getResponseCode();

          if(rescode>=400) {
            System.out.println(url + "---> is broken link");
          }else {
            System.out.println(url + "---> is valid link");
          }
        }
    }
}

        

Download Different Files in Chrome and FireFox

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.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;

class Selenium {
  public static void main(String[] args) {

    System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();

      driver.get("http://demo.automationtesting.in/FileDownload.html");
      driver.findElement(By.xpath("//*[@id=\"textbox\"]")).sendKeys("Testing text file");
      driver.findElement(By.xpath("//*[@id=\"createTxt\"]")).click();
      driver.findElement(By.xpath("//*[@id=\"link-to-download\"]")).click();

    FirefoxProfile profile = new FirefoxProfile();
    profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");
    profile.setPreference("browser.download.manager.showWhenStarting", false);
    profile.setPreference("pdfjs.disabled", true);

    FirefoxOptions option = new FirefoxOptions();
    option.setProfile(profile);

      System.setProperty("webdriver.gecko.driver", "E:\\Drivers\\geckodriver.exe");
    WebDriver driver = new FirefoxDriver(option);
    driver.manage().window().maximize();

      driver.get("http://demo.automationtesting.in/FileDownload.html");
      driver.findElement(By.xpath("//*[@id=\"textbox\"]")).sendKeys("Testing text file");
      driver.findElement(By.xpath("//*[@id=\"createTxt\"]")).click();
      driver.findElement(By.xpath("//*[@id=\"link-to-download\"]")).click();

  }
}

Create Your Own Dynamic XPATH in selenium

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.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;

class Selenium {
  public static void main(String[] args) {

    System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();

    driver.get("file:///C:/Users/user/Desktop/Selenium.html");

    // driver.findElement(By.xpath("//input[@type='text']")).sendKeys("Abhishek");
    // driver.findElement(By.xpath("//input[@placeholder='Name']")).sendKeys("Abhishek");

    // driver.findElement(By.xpath("//button[text()='Login with Google']")).click();
    //driver.findElement(By.xpath("button[contains(text(),'kjasg')]")).click();
    //driver.findElement(By.xpath("button[starts-with(text(),'kjasg')]")).click();
    //driver.findElement(By.xpath("button[ends-with(text(),'kjasg')]")).click();

    //input[@id='login']/following-sibling::button
    //input[@id='login']/preceding-sibling::button

    //input[@id='login']/parent::form

    //input[@type='text' and @placeholder='surname']
  }
}

Upload Files Using sikuli in selenium

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.sikuli.script.FindFailed;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;

class Selenium {
  public static void main(String[] args) throws FindFailed {

    System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();

    driver.get("file:///C:/Users/user/Desktop/Selenium.html");

    Actions act = new Actions(driver);

    act.click(driver.findElement(By.xpath("//*[@id=\'file\']"))).build().perform();

    Pattern p1 = new Pattern("C:\\Users\\user\\Desktop\\ImageRecog\\textbox.PNG");
    Pattern p2 = new Pattern("C:\\Users\\user\\Desktop\\ImageRecog\\openbotton.PNG");

    Screen sc = new Screen();

    sc.type(p1, "E:\\Abhishek Project\\Base Paper final.pdf");
    sc.click(p2);
  }
}

Handle Video Controls Using sikuli in selenium

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.sikuli.script.FindFailed;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;

class Selenium {
  public static void main(String[] args) throws FindFailed {

    System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();

    driver.get("file:///C:/Users/user/Desktop/Selenium.html");

    Pattern p1 = new Pattern("C:\\Users\\user\\Desktop\\Sikuli\\play.PNG");
    Pattern p2 = new Pattern("C:\\Users\\user\\Desktop\\Sikuli\\mute.PNG");
    Pattern p3 = new Pattern("C:\\Users\\user\\Desktop\\Sikuli\\maximize.PNG");

    Screen sc = new Screen();

    sc.click(p1);
    sc.click(p2);
    sc.click(p3);

  }
}

Read Data from MS-Excel in selenium

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

class Selenium {
  public static void main(String[] args) throws IOException {

//    	System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\chromedriver.exe");
//    	WebDriver driver = new ChromeDriver();
//    	driver.manage().window().maximize();
//    	driver.get("file:///C:/Users/user/Desktop/Selenium.html");

    FileInputStream file = new FileInputStream("C:\\Users\\user\\Desktop\\EmpInfo.xlsx");

    XSSFWorkbook wb = new XSSFWorkbook(file);

    XSSFSheet s = wb.getSheetAt(0);

    int row = s.getLastRowNum();

    int column = s.getRow(0).getLastCellNum();

    for(int i=0; i<=row; i++) { // read to use each row
      XSSFRow currentrow = s.getRow(i);

      for(int j=0; j<column; j++) { 	// read to use each cell on current row
        String value = currentrow.getCell(j).toString();
        System.out.print(value+"   ");
      }
      System.out.println();
    }

  }
}

Read Data from Excel in selenium

import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

class Selenium {
  public static void main(String[] args) throws IOException {

    System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("http://localhost:8084/KothaAbhishekProject/");

    FileInputStream file = new FileInputStream("C:\\Users\\user\\Desktop\\EmpInfo.xlsx");
    XSSFWorkbook workbook = new XSSFWorkbook(file);
    XSSFSheet sheet = workbook.getSheet("Sheet3");

    int rowcount = sheet.getLastRowNum();

    for(int i=1; i<=rowcount; i++) {
      XSSFRow row = sheet.getRow(i);

      String cell1 = row.getCell(0).getStringCellValue();
      String cell2 = row.getCell(1).getStringCellValue();
      String cell3 = row.getCell(2).getStringCellValue();
      int cell4 = (int)row.getCell(3).getNumericCellValue();
      String cell5 = row.getCell(4).getStringCellValue();

      driver.findElement(By.xpath("//input[@name='name']")).sendKeys(cell1);
      driver.findElement(By.xpath("//input[@name='pwd']")).sendKeys(cell2);
      driver.findElement(By.xpath("//input[@name='email']")).sendKeys(cell3);
      driver.findElement(By.xpath("//input[@name='number']")).sendKeys(String.valueOf(cell4));
//    		driver.findElement(By.xpath("//input[@name='gender']")).sendKeys(cell5).click();

      List radiobutton = driver.findElements(By.name("gender"));
      int size = radiobutton.size();

      for(int j=0; j<size; j++) {
        String val = radiobutton.get(j).getAttribute("value");

        if(val.equalsIgnoreCase(cell5)) {
          radiobutton.get(j).click();
          break;
        }

      }

      driver.findElement(By.xpath("//input[@name='Register']")).click();

      driver.get("http://localhost:8084/KothaAbhishekProject/");

    }
    driver.close();

    workbook.close();

  }
}

Write Data into Excel in selenium

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

class Selenium {
  public static void main(String[] args) throws IOException{

    System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("http://localhost:8084/PracticeApplication/");

    FileInputStream file = new FileInputStream("C:\\Users\\user\\Desktop\\EmpInfo.xlsx");
    XSSFWorkbook workbook = new XSSFWorkbook(file);
    XSSFSheet sheet = workbook.getSheet("Sheet4");

    int rowcount = sheet.getLastRowNum();

    for(int i=1; i<=rowcount; i++) {

      XSSFRow row = sheet.getRow(i);

      String uname = row.getCell(0).getStringCellValue();
      String upassword = row.getCell(1).getStringCellValue();

      driver.findElement(By.xpath("//input[@name='name']")).sendKeys(uname);
      driver.findElement(By.xpath("//input[@name='pwd']")).sendKeys(upassword);

      driver.findElement(By.xpath("//input[@name='Login']")).click();

      String message= driver.findElement(By.xpath("//span[@class='error']")).getText();

      if(message.equalsIgnoreCase("Valid User")) {
        sheet.getRow(i).createCell(2).setCellValue("Pass");
      }else {
        sheet.getRow(i).createCell(2).setCellValue("Fail");
      }

      FileOutputStream fout = new FileOutputStream("C:\\Users\\user\\Desktop\\EmpInfo.xlsx");

      workbook.write(fout);

      driver.get("http://localhost:8084/PracticeApplication/");
    }

    workbook.close();
  }
}

Robot class in selenium

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

class Selenium {
  public static void main(String[] args) throws AWTException, InterruptedException{

    System.setProperty("webdriver.gecko.driver", "E:\\Drivers\\geckodriver.exe");
    WebDriver driver = new FirefoxDriver();
    driver.manage().window().maximize();
    driver.get("http://demo.automationtesting.in/FileDownload.html");

    driver.findElement(By.xpath("//*[@id=\"textbox\"]")).sendKeys("Kotha Abhishek");
    driver.findElement(By.xpath("//*[@id=\"createTxt\"]")).click();
    driver.findElement(By.xpath("//*[@id=\"link-to-download\"]")).click();

    Robot robot = new Robot();
    Thread.sleep(3000);
    robot.keyPress(KeyEvent.VK_DOWN);
    Thread.sleep(3000);
    robot.keyPress(KeyEvent.VK_TAB);
    Thread.sleep(3000);
    robot.keyPress(KeyEvent.VK_TAB);
    Thread.sleep(3000);
    robot.keyPress(KeyEvent.VK_TAB);
    Thread.sleep(3000);
    robot.keyPress(KeyEvent.VK_ENTER);

  }
}

Upload or Download using Robot Class in selenium

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

class Selenium {
  public static void main(String[] args) throws AWTException {

    System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("file:///C:/Users/user/Desktop/Selenium.html");

    Actions act = new Actions(driver);
    act.click(driver.findElement(By.xpath("//*[@id=\"upload\"]"))).build().perform();

    Robot robot = new Robot();

    StringSelection select = new StringSelection("C:\\Users\\user\\Desktop\\Abhishek.jpg");
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(select, null); //ctrl+c

    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_V);   //ctrl+v
    robot.keyRelease(KeyEvent.VK_CONTROL);
    robot.keyRelease(KeyEvent.VK_V);
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);


  }
}

Calendar or Date Picker in selenium

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

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

    System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("https://jqueryui.com/datepicker/");

    String date = "32-December-2020";
    String arr[] = date.split("-");			// index 0

    driver.switchTo().frame(0);			// frame swift

    driver.findElement(By.xpath("//*[@id=\'datepicker\']")).click();

    String month = driver.findElement(By.xpath("//*[@id=\'ui-datepicker-div\']/div/div/span[1]")).getText();
    String year = driver.findElement(By.xpath("//*[@id=\'ui-datepicker-div\']/div/div/span[2]")).getText();
    int rows = driver.findElements(By.xpath("//table[@class='ui-datepicker-calendar']/tbody/tr")).size();
    int cols=7;

    boolean flag=false;

    while(true) {
      if(month.equals(arr[1]) && year.equals(arr[2])) {
        for(int i=1; i<=rows; i++) {			// rows tr
          for(int j=1; j<=cols; j++) {		// columns
            String day = driver.findElement(By.xpath("//table[@class='ui-datepicker-calendar']/tbody/tr["+i+"]/td["+j+"]")).getText();

            if(day.equals(arr[0])) {
              driver.findElement(By.xpath("//table[@class='ui-datepicker-calendar']/tbody/tr["+i+"]/td["+j+"]")).click();
              flag=true;
              break;		// columns stop (inner for loop)
            }
          }
        if(flag) {				// stops rows
          break;				// rows stops (outer for loop)
        }
        }
        if(flag) {
          System.out.println("success");
          break;				// while loop stop
        }else {
          System.out.println("Please Enter Correct Date");
          driver.close();
          break;
        }
      }else {
        driver.findElement(By.xpath("//*[@id=\'ui-datepicker-div\']/div/a[2]/span")).click();
        month = driver.findElement(By.xpath("//*[@id=\'ui-datepicker-div\']/div/div/span[1]")).getText();
        year = driver.findElement(By.xpath("//*[@id=\'ui-datepicker-div\']/div/div/span[2]")).getText();
        rows = driver.findElements(By.xpath("//table[@class='ui-datepicker-calendar']/tbody/tr")).size();
      }

    }
  }
}
import java.util.List;

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

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

    System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("https://jqueryui.com/datepicker/#other-months");

    String date = "29-February-2024";
    String arr[] = date.split("-");			// index 0

    driver.switchTo().frame(0);			// frame swift

    driver.findElement(By.xpath("//*[@id=\'datepicker\']")).click();

    String month = driver.findElement(By.xpath("//*[@id=\'ui-datepicker-div\']/div/div/span[1]")).getText();
    String year = driver.findElement(By.xpath("//*[@id=\'ui-datepicker-div\']/div/div/span[2]")).getText();

    boolean flag=false; 	// to stop program execution

    while(true) {
      if(month.equals(arr[1]) && year.equals(arr[2])) {

      List days = driver.findElements(By.xpath("//table[@class='ui-datepicker-calendar']/tbody/tr/td[not(contains(@class,' ui-datepicker-other-month '))]"));
      int size = days.size();

      for(int i=0; i<size; i++) {			// iterate LIST
        WebElement currentday = days.get(i);	// reads current webelement
        String day = currentday.getText();

        if(day.equals(arr[0])) {
          currentday.click();
          flag=true;
          break;		// stops for loop
        }
      }
        if(flag) {
          System.out.println("Success");
          break;			// stops while loop
        }else {
          System.out.println("Please Enter Valid Date");
          driver.close();
          break;			// stops while loop
        }
      }else {
        driver.findElement(By.xpath("//*[@id=\'ui-datepicker-div\']/div/a[2]/span")).click();
        month = driver.findElement(By.xpath("//*[@id=\'ui-datepicker-div\']/div/div/span[1]")).getText();
        year = driver.findElement(By.xpath("//*[@id=\'ui-datepicker-div\']/div/div/span[2]")).getText();
      }

    }
  }
}
import java.util.List;

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.support.ui.Select;

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

    System.setProperty("webdriver.chrome.driver", "E:\\Drivers\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("https://jqueryui.com/datepicker/#dropdown-month-year");

    String date = "29-Feb-2024";		//My birthday
    String arr[] = date.split("-");			// index 0

    driver.switchTo().frame(0);			// frame swift

    driver.findElement(By.xpath("//*[@id=\'datepicker\']")).click();

    Select month = new Select(driver.findElement(By.xpath("//*[@id=\"ui-datepicker-div\"]/div/div/select[1]")));

    month.selectByVisibleText(arr[1]);

    Select year = new Select(driver.findElement(By.xpath("//*[@id=\"ui-datepicker-div\"]/div/div/select[2]")));

    year.selectByVisibleText(arr[2]);

    List days = driver.findElements(By.xpath("//table[@class='ui-datepicker-calendar']/tbody/tr/td"));
    int size = days.size();

    boolean flag=false;

    for(int i=0; i<size; i++) {
      WebElement currentday = days.get(i);
      String day = currentday.getText();

      if(day.equals(arr[0])) {
        currentday.click();
        flag=true;
        break;
      }
    }
    if(flag) {
      System.out.println("Success");
    }else {
      driver.close();
      System.out.println("Please Enter a Valid Date");
    }
  }
}