Introduction to Web Elements

Welcome to today’s session on Interacting with Web Elements using Selenium WebDriver with Java. Building upon our previous discussions on locating web elements using various strategies like ID, Name, CSS Selectors, and XPath, today we will delve into how to interact with these elements effectively. Understanding how to interact with web elements is crucial for automating user actions and validating web applications.



Overview of Selenium WebDriver Methods

Selenium WebDriver provides a rich set of methods categorized into different types based on their functionality. The primary categories we will cover today are:

  • Get Methods
  • Conditional Methods
  • Browser Methods

Get Methods

  • get(): Launches a web page in the browser.
  • getTitle(): Retrieves the title of the current page.
  • getCurrentUrl(): Retrieves the URL of the current page.
  • getPageSource(): Retrieves the source code of the current page.
  • getWindowHandle(): Retrieves the handle (unique ID) of the current browser window.
  • getWindowHandles(): Retrieves handles of all open browser windows.

Conditional Methods

  • isDisplayed(): Checks if an element is visible on the page.
  • isEnabled(): Checks if an element is enabled and can interact with.
  • isSelected(): Checks if an element (checkbox/radio button) is selected.
  • getText(): Retrieves the visible text of an element.

Browser Methods

  • close(): Closes the current browser window.
  • quit(): Closes all browser windows and ends the WebDriver session.

Detailed Explanation of Methods

Get Methods

get(String url): Launches a specified URL in the browser.

driver.get("https://www.example.com");

getTitle(): Retrieves the title of the current web page.

String pageTitle = driver.getTitle();
System.out.println("Page Title: " + pageTitle);

getCurrentUrl(): Retrieves the URL of the current web page.

String currentURL = driver.getCurrentUrl();
System.out.println("Current URL: " + currentURL);

getPageSource(): Retrieves the HTML source code of the current page.

String pageSource = driver.getPageSource();
System.out.println("Page Source Length: " + pageSource.length());

getWindowHandle(): Retrieves the unique handle (ID) of the current browser window.

String windowHandle = driver.getWindowHandle();
System.out.println("Window Handle: " + windowHandle);

getWindowHandles(): Retrieves handles of all open browser windows.

Set windowHandles = driver.getWindowHandles();
for (String handle : windowHandles) {
    System.out.println("Window Handle: " + handle);
}

Conditional Methods

isDisplayed(): Checks if a web element is visible on the page.

WebElement logo = driver.findElement(By.xpath("//img[@id='logo']"));
boolean isLogoDisplayed = logo.isDisplayed();
System.out.println("Is Logo Displayed: " + isLogoDisplayed);

isEnabled(): Checks if a web element is enabled and can be interacted with.

WebElement submitButton = driver.findElement(By.id("submitBtn"));
boolean isSubmitEnabled = submitButton.isEnabled();
System.out.println("Is Submit Button Enabled: " + isSubmitEnabled);

isSelected(): Checks if a checkbox or radio button is selected.

WebElement checkbox = driver.findElement(By.id("subscribe"));
boolean isCheckboxSelected = checkbox.isSelected();
System.out.println("Is Checkbox Selected: " + isCheckboxSelected);

getText(): Retrieves the visible text of a web element.

WebElement welcomeMessage = driver.findElement(By.id("welcomeMsg"));
String message = welcomeMessage.getText();
System.out.println("Welcome Message: " + message);

Browser Methods

close(): Closes the current browser window.

driver.close();

quit(): Closes all browser windows and ends the WebDriver session.

driver.quit();

Practical Examples

Example 1: Using Get Methods

Objective: Launch a web page, retrieve its title, URL, and page source.

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

public class GetMethodsExample {
    public static void main(String[] args) throws InterruptedException {
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.orangehrm.com/orangehrm-30-day-trial/");
        String title = driver.getTitle();
        System.out.println("Page Title: " + title);
        String currentURL = driver.getCurrentUrl();
        System.out.println("Current URL: " + currentURL);
        String pageSource = driver.getPageSource();
        System.out.println("Page Source Length: " + pageSource.length());
        String windowHandle = driver.getWindowHandle();
        System.out.println("Window Handle: " + windowHandle);
        driver.quit();
    }
}

Example 2: Using Conditional Methods

Objective: Verify the visibility and state of radio buttons and checkboxes.

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

public class ConditionalMethodsExample {
    public static void main(String[] args) throws InterruptedException {
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.orangehrm.com/orangehrm-30-day-trial/");
        driver.manage().window().maximize();
        WebElement logo = driver.findElement(By.xpath("//img[@alt='OrangeHRM']"));
        System.out.println("Is Logo Displayed: " + logo.isDisplayed());
        WebElement maleRadio = driver.findElement(By.xpath("//input[@id='male']"));
        System.out.println("Is Male Radio Button Selected: " + maleRadio.isSelected());
        WebElement femaleRadio = driver.findElement(By.xpath("//input[@id='female']"));
        System.out.println("Is Female Radio Button Selected: " + femaleRadio.isSelected());
        maleRadio.click();
        femaleRadio.click();
        driver.quit();
    }
}

Example 3: Using Browser Methods

Objective: Demonstrate the difference between close() and quit() methods.

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

public class BrowserMethodsExample {
    public static void main(String[] args) throws InterruptedException {
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.orangehrm.com/orangehrm-30-day-trial/");
        driver.findElement(By.linkText("OrangeHRM Inc")).click();
        Thread.sleep(5000);
        String parentWindow = driver.getWindowHandle();
        System.out.println("Parent Window Handle: " + parentWindow);
        Set allWindows = driver.getWindowHandles();
        driver.close();
        driver.quit();
    }
}

Handling Multiple Browser Windows

When automating scenarios that involve multiple browser windows or tabs, it’s essential to manage window handles effectively. Here’s how you can handle multiple windows:

  • Retrieve All Window Handles:
    Set allWindowHandles = driver.getWindowHandles();
  • Iterate Through Window Handles:
    for (String handle : allWindowHandles) {
                driver.switchTo().window(handle);
            }
  • Switch to a Specific Window:
    driver.switchTo().window(desiredWindowHandle);

Assignment

Objective: Apply the methods learned today to automate interactions on a practice web page.

Tasks:

  • Navigate to the Practice Page: Open the URL: Test Automation Practice
  • Use Get Methods:
    • Retrieve and print the page title using getTitle().
    • Retrieve and print the current URL using getCurrentUrl().
    • Retrieve and print the page source length using getPageSource().
  • Handle Multiple Windows:
    • Click on a link that opens a new browser window or tab.
    • Retrieve and print all window handles using getWindowHandles().
    • Switch to the new window and perform an action.

Next Steps

Congratulations on mastering the basics of interacting with web elements! In our next session, we will explore:

  • Navigational Methods:
    • navigate().to(): Similar to get(), but allows more control.
    • navigate().back(): Navigates to the previous page.
    • navigate().forward(): Navigates to the next page.
    • navigate().refresh(): Refreshes the current page.

Conclusion

Today, we covered essential Selenium WebDriver methods for interacting with web elements:

  • Get Methods: Retrieve information from the web page and manage browser windows.
  • Conditional Methods: Verify the state and visibility of web elements.
  • Browser Methods: Control the browser’s behavior by closing windows.

Key Takeaways:

  • Element Identification: Accurately locating web elements is the foundation of effective automation.
  • Method Application: Appropriately applying WebDriver methods ensures smooth interaction with the browser and web elements.
  • Handling Multiple Windows: Managing window handles is crucial when dealing with multi-window scenarios.
  • Validation: Using conditional methods to validate the state of elements enhances the reliability of your tests.

Happy Automating!