Certainly! Based on the comprehensive tutorial you’ve provided on handling date pickers in Selenium WebDriver using Java, let’s address the two assignments you’ve outlined. We’ll walk through each assignment step-by-step, providing detailed explanations and sample code implementations to help you solidify your understanding.

1. Assignment 1: Handling a Specific Calendar Date Picker

• Objective

Automate the selection of a specific date (year, month, and day) using a customized date picker within a web application. This involves:

  1. Selecting the Year and Month:
    • Navigating through the date picker to reach the desired year and month.
    • Handling both past and future dates based on the requirement.
  2. Selecting the Day:
    • Choosing the specific day from the available dates once the correct month and year are displayed.

• Scenario Overview

You have a web application with a date picker that:

  • Is embedded within an <iframe>.
  • Allows selection of both past and future dates.
  • Requires handling the date picker through dynamic elements (e.g., navigating months/years using arrow buttons).

• Implementation Steps

  1. Setup Selenium WebDriver:
    • Initialize the WebDriver (e.g., ChromeDriver).
    • Configure implicit waits and maximize the browser window.
  2. Navigate to the Target Page:
    • Open the URL where the date picker is located.
  3. Handle <iframe> Switching:
    • Switch the WebDriver context to the <iframe> containing the date picker.
  4. Interact with the Date Picker:
    • Method 1: Using sendKeys to input the date directly into the input field (if supported).
    • Method 2: Using the date picker UI to select the desired date by:
      • Selecting the correct year and month.
      • Selecting the specific day.
  5. Reusability:
    • Create user-defined methods to handle month/year selection and day selection.
    • Ensure these methods can be reused for multiple date pickers within the same application.

• Sample Code Implementation

Below is a comprehensive Java Selenium script that demonstrates handling a specific calendar date picker as per the assignment’s requirements.

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;
import java.time.Month;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class DatePickerHandler {

    public static void main(String[] args) {
        // 1. Setup WebDriver
        System.setProperty("webdriver.chrome.driver", "path_to_chromedriver"); // Update with your path
        WebDriver driver = new ChromeDriver();

        // 2. Configure WebDriver
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Implicit Wait

        try {
            // 3. Navigate to the Target Page
            driver.get("https://example.com/date-picker-page"); // Replace with actual URL

            // 4. Switch to the iframe containing the date picker
            driver.switchTo().frame("frameID_or_Name"); // Replace with actual frame ID or name

            // 5. Handle Date Picker

            // Method 1: Using sendKeys (if supported)
            WebElement dateInput = driver.findElement(By.xpath("//input[@id='date-input']")); // Update XPath as needed
            String dateToSelect = "05/20/2025"; // Format as per the input field's requirement
            dateInput.sendKeys(dateToSelect);

            // Verify if sendKeys worked; if not, proceed to Method 2
            // This verification can be done by checking the value of the input field
            String enteredDate = dateInput.getAttribute("value");
            if (!enteredDate.equals(dateToSelect)) {
                // Method 2: Using Date Picker UI
                selectDate(driver, "May", "2025", "20");
            }

            // Additional interactions can be performed here

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 6. Close the Browser
            driver.quit();
        }
    }

    /**
     * Method to select a specific date using the date picker UI.
     *
     * @param driver   WebDriver instance
     * @param month    Desired month (e.g., "May")
     * @param year     Desired year (e.g., "2025")
     * @param day      Desired day (e.g., "20")
     */
    public static void selectDate(WebDriver driver, String month, String year, String day) {
        // Click on the date picker input to open the calendar
        WebElement dateInput = driver.findElement(By.xpath("//input[@id='date-input']")); // Update XPath as needed
        dateInput.click();

        // Loop until the desired month and year are found
        while (true) {
            // Capture the currently displayed month and year
            String currentMonth = driver.findElement(By.xpath("//span[@class='ui-datepicker-month']")).getText();
            String currentYear = driver.findElement(By.xpath("//span[@class='ui-datepicker-year']")).getText();

            // Compare with the desired month and year
            int monthComparison = convertMonthToObject(month).compareTo(convertMonthToObject(currentMonth));
            int yearComparison = Integer.parseInt(year) - Integer.parseInt(currentYear);

            if (yearComparison == 0) {
                if (monthComparison == 0) {
                    break; // Desired month and year are displayed
                } else if (monthComparison > 0) {
                    // Desired month is in the future; click next
                    driver.findElement(By.xpath("//a[@title='Next']")).click();
                } else {
                    // Desired month is in the past; click previous
                    driver.findElement(By.xpath("//a[@title='Prev']")).click();
                }
            } else if (yearComparison > 0) {
                // Desired year is in the future; click next
                driver.findElement(By.xpath("//a[@title='Next']")).click();
            } else {
                // Desired year is in the past; click previous
                driver.findElement(By.xpath("//a[@title='Prev']")).click();
            }
        }

        // Select the desired day
        List allDates = driver.findElements(By.xpath("//table[@class='ui-datepicker-calendar']//a"));
        for (WebElement date : allDates) {
            if (date.getText().equals(day)) {
                date.click();
                break;
            }
        }
    }

    /**
     * Converts a month name string to a Month object.
     *
     * @param monthStr Month name (e.g., "January")
     * @return Month object
     */
    public static Month convertMonthToObject(String monthStr) {
        Map<String, Month> monthMap = new HashMap<>();
        monthMap.put("January", Month.JANUARY);
        monthMap.put("February", Month.FEBRUARY);
        monthMap.put("March", Month.MARCH);
        monthMap.put("April", Month.APRIL);
        monthMap.put("May", Month.MAY);
        monthMap.put("June", Month.JUNE);
        monthMap.put("July", Month.JULY);
        monthMap.put("August", Month.AUGUST);
        monthMap.put("September", Month.SEPTEMBER);
        monthMap.put("October", Month.OCTOBER);
        monthMap.put("November", Month.NOVEMBER);
        monthMap.put("December", Month.DECEMBER);

        return monthMap.getOrDefault(monthStr, null);
    }
}

• Explanation

  1. Setup and Configuration:
    • WebDriver Initialization: Initializes the ChromeDriver. Ensure that the chromedriver executable path is correctly specified.
    • Implicit Waits: Configures implicit waits to handle dynamic element loading.
    • Browser Maximization: Maximizes the browser window for better visibility.
  2. Navigating to the Target Page:
    • URL Navigation: Opens the specified URL where the date picker is located.
  3. Handling <iframe> Switching:
    • Frame Identification: Switches to the <iframe> containing the date picker using its id or name. Replace “frameID_or_Name” with the actual identifier.
  4. Interacting with the Date Picker:
    • Method 1 – sendKeys:
      • Attempts to input the desired date directly into the input field.
      • Verification: Checks if the input was successful by comparing the entered value with the desired date.
    • Method 2 – Date Picker UI:
      • Opening the Date Picker: Clicks on the date input to open the calendar UI.
      • Selecting Year and Month:
        • Captures the currently displayed month and year.
        • Compares them with the desired month and year.
        • Navigates forward or backward by clicking the respective arrow buttons until the desired month and year are displayed.
      • Selecting the Day:
        • Iterates through all available dates and clicks on the desired day.
  5. Reusability:
    • selectDate Method: Encapsulates the logic for selecting a date, making it reusable across different date pickers with similar structures.
    • convertMonthToObject Method: Converts month names from strings to Month enum objects to facilitate accurate comparisons.

• Key Points

  • Dynamic Element Handling: The script dynamically navigates through the date picker UI based on the desired date, ensuring flexibility across different date selections.
  • Error Handling: Incorporate additional error handling (e.g., handling cases where the desired date is not available) as needed.
  • Modularity: The use of user-defined methods enhances code readability and reusability.

2. Assignment 2: Handling an End-to-End Booking Application

• Objective

Automate the entire process of filling out a booking form that includes various elements such as radio buttons, checkboxes, input fields, dropdowns, auto-suggestions, and multiple date pickers. The goal is to:

  1. Interact with Various Web Elements:
    • Select radio buttons (e.g., gender).
    • Check checkboxes.
    • Input text into fields (e.g., first name, last name).
    • Handle dropdowns and auto-suggestions (e.g., selecting cities).
    • Handle multiple date pickers for departure and return dates.
  2. Ensure Reusability and Maintainability:
    • Utilize user-defined methods for repetitive tasks.
    • Organize code for clarity and scalability.

• Scenario Overview

You have a booking application form that includes:

  • Radio Buttons: For selecting options like gender.
  • Checkboxes: For agreeing to terms or selecting additional services.
  • Input Fields: For entering personal information.
  • Dropdowns and Auto-Suggestions: For selecting cities with auto-complete features.
  • Multiple Date Pickers: For selecting departure and return dates, each possibly with different configurations.

• Implementation Steps

  1. Setup Selenium WebDriver:
    • Initialize the WebDriver (e.g., ChromeDriver).
    • Configure implicit waits and maximize the browser window.
  2. Navigate to the Booking Form Page:
    • Open the URL where the booking form is located.
  3. Interact with Web Elements:
    • Radio Buttons: Select the desired option.
    • Checkboxes: Check or uncheck as required.
    • Input Fields: Use sendKeys to input text.
    • Dropdowns and Auto-Suggestions:
      • For standard dropdowns, use the Select class.
      • For auto-suggestions, input partial text and select from the suggestions.
    • Date Pickers:
      • Handle multiple date pickers using reusable methods (as developed in Assignment 1).
  4. Submit the Form:
    • Click the “Place Order” or equivalent button to submit the form.
  5. Verification (Optional):
    • Verify that the form submission was successful by checking for confirmation messages or redirects.

• Sample Code Implementation

Below is a sample Java Selenium script that automates the end-to-end booking process as per the assignment’s requirements.

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;
import java.time.Month;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class BookingFormAutomation {

    public static void main(String[] args) {
        // 1. Setup WebDriver
        System.setProperty("webdriver.chrome.driver", "path_to_chromedriver"); // Update with your path
        WebDriver driver = new ChromeDriver();

        // 2. Configure WebDriver
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Implicit Wait

        try {
            // 3. Navigate to the Booking Form Page
            driver.get("https://example.com/booking-form"); // Replace with actual URL

            // 4. Interact with Web Elements

            // a. Select Radio Button (e.g., Gender)
            WebElement maleRadio = driver.findElement(By.xpath("//input[@name='gender'][@value='Male']"));
            maleRadio.click();

            // b. Check Checkbox (e.g., Agree to Terms)
            WebElement termsCheckbox = driver.findElement(By.xpath("//input[@type='checkbox'][@id='agree']"));
            if (!termsCheckbox.isSelected()) {
                termsCheckbox.click();
            }

            // c. Input Text into Fields
            WebElement firstName = driver.findElement(By.xpath("//input[@id='first-name']"));
            firstName.sendKeys("John");

            WebElement lastName = driver.findElement(By.xpath("//input[@id='last-name']"));
            lastName.sendKeys("Doe");

            WebElement email = driver.findElement(By.xpath("//input[@id='email']"));
            email.sendKeys("john.doe@example.com");

            // d. Handle Dropdown (e.g., Country Selection)
            Select countryDropdown = new Select(driver.findElement(By.xpath("//select[@id='country']")));
            countryDropdown.selectByVisibleText("United States");

            // e. Handle Auto-Suggestions (e.g., From City)
            WebElement fromCityInput = driver.findElement(By.xpath("//input[@id='from-city']"));
            fromCityInput.sendKeys("Del");
            // Wait for auto-suggestions to load (consider using explicit waits)
            Thread.sleep(2000); // Replace with explicit wait for better practice
            List fromSuggestions = driver.findElements(By.xpath("//ul[@id='from-city-suggestions']/li"));
            for (WebElement suggestion : fromSuggestions) {
                if (suggestion.getText().equals("Delhi")) {
                    suggestion.click();
                    break;
                }
            }

            // f. Handle Auto-Suggestions (e.g., To City)
            WebElement toCityInput = driver.findElement(By.xpath("//input[@id='to-city']"));
            toCityInput.sendKeys("New");
            Thread.sleep(2000); // Replace with explicit wait
            List toSuggestions = driver.findElements(By.xpath("//ul[@id='to-city-suggestions']/li"));
            for (WebElement suggestion : toSuggestions) {
                if (suggestion.getText().equals("New York")) {
                    suggestion.click();
                    break;
                }
            }

            // g. Handle Date Pickers
            // Departure Date Picker
            selectDate(driver, "May", "2025", "20", "//input[@id='departure-date']");

            // Return Date Picker
            selectDate(driver, "June", "2025", "15", "//input[@id='return-date']");

            // h. Submit the Form
            WebElement submitButton = driver.findElement(By.xpath("//button[@id='place-order']"));
            submitButton.click();

            // i. Verification (Optional)
            // Example: Check for confirmation message
            WebElement confirmationMessage = driver.findElement(By.xpath("//div[@class='confirmation']"));
            if (confirmationMessage.isDisplayed()) {
                System.out.println("Booking successfully submitted!");
            } else {
                System.out.println("Booking submission failed.");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 5. Close the Browser
            driver.quit();
        }
    }

    /**
     * Method to select a specific date using the date picker UI.
     *
     * @param driver          WebDriver instance
     * @param month           Desired month (e.g., "May")
     * @param year            Desired year (e.g., "2025")
     * @param day             Desired day (e.g., "20")
     * @param dateInputXPath  XPath of the date input field
     */
    public static void selectDate(WebDriver driver, String month, String year, String day, String dateInputXPath) throws InterruptedException {
        // Click on the date picker input to open the calendar
        WebElement dateInput = driver.findElement(By.xpath(dateInputXPath));
        dateInput.click();

        // Loop until the desired month and year are found
        while (true) {
            // Capture the currently displayed month and year
            String currentMonth = driver.findElement(By.xpath("//span[@class='ui-datepicker-month']")).getText();
            String currentYear = driver.findElement(By.xpath("//span[@class='ui-datepicker-year']")).getText();

            // Compare with the desired month and year
            int monthComparison = convertMonthToObject(month).compareTo(convertMonthToObject(currentMonth));
            int yearComparison = Integer.parseInt(year) - Integer.parseInt(currentYear);

            if (yearComparison == 0) {
                if (monthComparison == 0) {
                    break; // Desired month and year are displayed
                } else if (monthComparison > 0) {
                    // Desired month is in the future; click next
                    driver.findElement(By.xpath("//a[@title='Next']")).click();
                } else {
                    // Desired month is in the past; click previous
                    driver.findElement(By.xpath("//a[@title='Prev']")).click();
                }
            } else if (yearComparison > 0) {
                // Desired year is in the future; click next
                driver.findElement(By.xpath("//a[@title='Next']")).click();
            } else {
                // Desired year is in the past; click previous
                driver.findElement(By.xpath("//a[@title='Prev']")).click();
            }

            // Optional: Wait for the calendar to update
            Thread.sleep(1000); // Replace with explicit wait for better practice
        }

        // Select the desired day
        List allDates = driver.findElements(By.xpath("//table[@class='ui-datepicker-calendar']//a"));
        for (WebElement date : allDates) {
            if (date.getText().equals(day)) {
                date.click();
                break;
            }
        }
    }

    /**
     * Converts a month name string to a Month object.
     *
     * @param monthStr Month name (e.g., "January")
     * @return Month object
     */
    public static Month convertMonthToObject(String monthStr) {
        Map<String, Month> monthMap = new HashMap<>();
        monthMap.put("January", Month.JANUARY);
        monthMap.put("February", Month.FEBRUARY);
        monthMap.put("March", Month.MARCH);
        monthMap.put("April", Month.APRIL);
        monthMap.put("May", Month.MAY);
        monthMap.put("June", Month.JUNE);
        monthMap.put("July", Month.JULY);
        monthMap.put("August", Month.AUGUST);
        monthMap.put("September", Month.SEPTEMBER);
        monthMap.put("October", Month.OCTOBER);
        monthMap.put("November", Month.NOVEMBER);
        monthMap.put("December", Month.DECEMBER);

        return monthMap.getOrDefault(monthStr, null);
    }
}

• Explanation

  1. Setup and Configuration:
    • WebDriver Initialization: Initializes the ChromeDriver. Ensure that the chromedriver executable path is correctly specified.
    • Implicit Waits: Configures implicit waits to handle dynamic element loading.
    • Browser Maximization: Maximizes the browser window for better visibility.
  2. Navigating to the Booking Form Page:
    • URL Navigation: Opens the specified URL where the booking form is located.
  3. Interacting with Web Elements:
    • Radio Buttons:
      • Locates and selects the “Male” radio button using its XPath.
    • Checkboxes:
      • Locates and checks the “Agree to Terms” checkbox if it’s not already selected.
    • Input Fields:
      • Inputs text into the “First Name,” “Last Name,” and “Email” fields using sendKeys.
    • Dropdowns:
      • Handles standard dropdowns (e.g., Country selection) using the Select class.
    • Auto-Suggestions:
      • Inputs partial text into the “From City” and “To City” fields.
      • Waits for auto-suggestions to load (using Thread.sleep for simplicity; consider using explicit waits for better practice).
      • Iterates through the suggestions and selects the desired option by matching the text.
    • Date Pickers:
      • Handles multiple date pickers (e.g., Departure Date and Return Date) by calling the reusable selectDate method.
  4. Submitting the Form:
    • Locates and clicks the “Place Order” button to submit the form.
  5. Verification (Optional):
    • Checks for the presence of a confirmation message to verify successful submission.
  6. Reusability and Modularity:
    • selectDate Method:
      • Encapsulates the logic for selecting a date, making it reusable for multiple date pickers.
      • Accepts parameters for the desired month, year, day, and the XPath of the date input field.
    • convertMonthToObject Method:
      • Converts month names from strings to Month enum objects to facilitate accurate comparisons.

• Key Points

  • Handling Multiple Date Pickers: By passing different XPaths and date values to the selectDate method, the same logic can handle multiple date pickers within the application.
  • Auto-Suggestions Handling: After typing partial text, the script waits for suggestions to load and selects the desired city by matching the suggestion text.
  • Error Handling: Incorporate additional error handling (e.g., verifying if suggestions are present) as needed.
  • Synchronization: Replace Thread.sleep with explicit waits (e.g., WebDriverWait) to handle dynamic loading more efficiently.

3. Best Practices Recap

  1. Use Explicit Waits Over Thread.sleep():
    • Enhances synchronization and reduces test execution time.
    • Example:
    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("elementID")));
  2. Prefer Reliable Locators:
    • Use By.id or By.name when available.
    • Use descriptive XPath or CSS selectors.
    • Avoid brittle locators that depend on dynamic attributes.
  3. Handle Exceptions Gracefully:
    • Prevents abrupt test failures and allows for better debugging.
    • Example:
    try {
        // Interaction code
    } catch (NoSuchElementException e) {
        System.out.println("Element not found: " + e.getMessage());
    }
  4. Avoid Hardcoding Values:
    • Use variables or external data sources for input values.
    • Parameterize test scripts.
  5. Maintain Clean and Readable Code:
    • Use descriptive variable and method names.
    • Comment complex logic or XPath expressions.
    • Organize code into reusable methods or Page Object Model (POM) structures.
  6. Use Page Object Model (POM):
    • Promotes reusability and separation of concerns.
    • Create separate classes for each page.
    • Encapsulate element locators and interaction methods within page classes.
  7. Regularly Update WebDriver and Browsers:
    • Ensures compatibility and leverages the latest features and fixes.
  8. Securely Handle Credentials:
    • Prevents exposure of sensitive information.
    • Use environment variables or encrypted storage solutions.
  9. Validate Actions:
    • Ensures that the intended actions (like selecting a checkbox) have been performed successfully.
    • Example:
    assert checkbox.isSelected() : "Checkbox was not selected.";
  10. Avoid Overcomplicating Locators:
    • Use the simplest locator that uniquely identifies an element.

4. Conclusion

Handling date pickers in Selenium WebDriver requires a clear understanding of the underlying HTML structure and the application’s specific behaviors. By creating reusable methods and adhering to best practices, you can efficiently automate complex date selection scenarios across different web applications.

Next Steps:

  • Practice Assignments: Implement the provided assignments to reinforce your understanding of date picker handling.
  • Explore Advanced Topics: Delve into handling more complex UI elements, integrating Selenium with testing frameworks like TestNG or JUnit, and leveraging the Page Object Model (POM) for better code organization.
  • Continuous Learning: Stay updated with Selenium WebDriver’s latest features and best practices to build efficient and robust automation scripts.

Happy Automating! 🚀