Popular Searches
Popular Course Categories
Popular Courses

WebDriver with Java

Selenium with Java

WebDriver with Java

WebDriver with Java is one of the most widely used approaches for automating web browsers with Selenium. Selenium WebDriver provides a programming interface through which Java programs can control browsers, locate web elements, perform user-like actions, navigate between pages, handle browser windows, work with alerts and frames, and validate web application behavior.

WebDriver communicates with browser-specific implementations and allows automation scripts to interact with browsers in a way that closely represents real user actions. Selenium supports major browsers through WebDriver, and the Java API provides an object-oriented interface for browser automation.

Course Resources: Selenium Training | Register for Course Demo


1. What is WebDriver?

WebDriver is a Selenium API used to control web browsers programmatically. It allows an automation script to open a browser, navigate to a URL, find elements, enter data, click buttons, read information, submit forms, manage windows, handle alerts, and perform many other browser operations.

WebDriver follows a browser automation architecture in which the Java Selenium client sends commands through the WebDriver API, which communicates with the appropriate browser implementation.

Java Selenium Program

        |

        v

Selenium WebDriver API

        |

        v

Browser Driver

        |

        v

Web Browser

        |

        v

Web Application


2. Why Use WebDriver with Java?

  • Java is widely used for enterprise application development and test automation.
  • Selenium provides a mature Java API for browser automation.
  • Java works well with TestNG and JUnit.
  • Maven can manage Selenium and testing dependencies.
  • Java supports object-oriented automation frameworks.
  • Java Selenium projects can be integrated with CI/CD tools.
  • Java is suitable for implementing Page Object Model and reusable automation components.


3. Important Components of Selenium WebDriver

ComponentPurpose
WebDriverControls the browser and provides browser-level operations.
WebElementRepresents an element present on a web page.
ByProvides locator strategies for finding elements.
ChromeDriverControls Google Chrome.
FirefoxDriverControls Mozilla Firefox.
EdgeDriverControls Microsoft Edge.
WebDriverWaitProvides explicit waiting functionality.
ExpectedConditionsProvides predefined conditions for explicit waits.


4. Selenium WebDriver Architecture

The Selenium WebDriver architecture contains several layers. A Java test program uses Selenium Java bindings to send commands to WebDriver. WebDriver communicates with the appropriate browser driver, and the browser driver communicates with the browser.

Java Automation Test

        |

        v

Selenium Java Bindings

        |

        v

WebDriver API

        |

        v

ChromeDriver / FirefoxDriver / EdgeDriver

        |

        v

Chrome / Firefox / Edge

        |

        v

Web Application

This architecture allows the same general automation concepts to be used across different supported browsers.


5. Prerequisites for WebDriver with Java

Before creating a Java Selenium project, install and configure the required development tools.

  • Java Development Kit (JDK)
  • Java IDE such as IntelliJ IDEA or Eclipse
  • Maven, when using a Maven project
  • A supported web browser
  • Selenium Java dependency

Modern Selenium setups can manage browser drivers through Selenium's driver management mechanisms, reducing the need for users to manually configure driver executable paths in many environments.


6. Creating a Maven Project

Maven is commonly used for Selenium Java projects because it manages project dependencies, builds, test execution, plugins, and project structure.

A typical Selenium Maven project contains the following structure:

selenium-java-project/

├── pom.xml

└── src/

    ├── main/

    │   └── java/

    └── test/

        └── java/

            └── tests/


7. Selenium Java Maven Dependency

The Selenium Java library can be added to a Maven project through the selenium-java artifact.

<dependency>

    <groupId>org.seleniumhq.selenium</groupId>

    <artifactId>selenium-java</artifactId>

    <version>YOUR_SELENIUM_VERSION</version>

</dependency>

Use the Selenium version selected for your project rather than hard-coding an outdated version in reusable training material.


8. Important Java Selenium Imports

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.WebDriverWait;

import org.openqa.selenium.support.ui.ExpectedConditions;

 

import java.time.Duration;

ImportPurpose
WebDriverProvides the main browser-control interface.
ChromeDriverCreates a Chrome browser session.
WebElementRepresents an HTML element.
ByProvides locator strategies.
WebDriverWaitCreates an explicit wait.
ExpectedConditionsProvides wait conditions.
DurationDefines wait durations.


9. Creating a WebDriver Object

The WebDriver interface is normally used as the variable type, while a browser-specific implementation such as ChromeDriver is used to create the browser session.

WebDriver driver = new ChromeDriver();

Using the interface type is useful because the test code can work with the common WebDriver API.


10. Launching the Browser

WebDriver driver = new ChromeDriver();

This creates a Chrome browser session. The browser driver handles communication between Selenium and the browser.


11. Opening a Website

The get() method navigates the browser to a specified URL.

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

Another navigation approach is:

driver.navigate().to("https://example.com");


12. Difference Between get() and navigate().to()

MethodPurpose
get()Loads a specified URL.
navigate().to()Navigates to a specified URL through the navigation interface.
navigate().back()Moves back in browser history.
navigate().forward()Moves forward in browser history.
navigate().refresh()Refreshes the current page.


13. Getting the Page Title

The getTitle() method returns the title of the current web page.

String title = driver.getTitle();

System.out.println(title);


14. Getting the Current URL

String currentUrl = driver.getCurrentUrl();

System.out.println(currentUrl);

This is useful when validating redirects and navigation behavior.


15. Finding Web Elements

Most Selenium operations begin by locating an element. Selenium Java provides the findElement() method for locating a single element.

WebElement username = driver.findElement(By.id("username"));

For multiple matching elements, use findElements().

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


16. Selenium Locators

Locators tell Selenium which element should be interacted with.

LocatorJava Syntax
IDBy.id("username")
NameBy.name("email")
Class NameBy.className("login-button")
Tag NameBy.tagName("button")
Link TextBy.linkText("Login")
Partial Link TextBy.partialLinkText("Log")
CSS SelectorBy.cssSelector("#username")
XPathBy.xpath("//input[@id='username']")


17. WebElement in Selenium Java

WebElement represents an element in the web page DOM. It provides methods for interacting with and reading information from the element.

WebElement username = driver.findElement(By.id("username"));

 

username.sendKeys("admin");

username.clear();

username.click();

 

String value = username.getAttribute("value");


18. Common WebElement Methods

MethodPurpose
click()Clicks an element.
sendKeys()Enters text or keyboard input.
clear()Clears an editable field.
getText()Returns visible text.
getAttribute()Returns an element attribute.
isDisplayed()Checks whether an element is displayed.
isEnabled()Checks whether an element is enabled.
isSelected()Checks whether a selectable element is selected.


19. Entering Data into a Text Box

WebElement username = driver.findElement(By.id("username"));

username.sendKeys("admin");

For password fields:

WebElement password = driver.findElement(By.id("password"));

password.sendKeys("admin123");


20. Clicking a Button

WebElement loginButton = driver.findElement(By.id("login"));

loginButton.click();

Selenium first locates the button and then sends the click command to the browser.


21. Reading Text from a Web Page

WebElement message = driver.findElement(By.id("message"));

String text = message.getText();

 

System.out.println(text);

This is commonly used for validation.


22. Browser Navigation

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

 

driver.navigate().to("https://example.org");

driver.navigate().back();

driver.navigate().forward();

driver.navigate().refresh();


23. Managing Browser Window

Selenium provides methods for maximizing, minimizing, fullscreen mode, and controlling window size.

driver.manage().window().maximize();

driver.manage().window().fullscreen();

For a specific window size:

driver.manage().window().setSize(new Dimension(1280, 720));


24. Browser Cookies

Selenium can interact with cookies through the WebDriver cookie API.

driver.manage().deleteAllCookies();

A cookie can also be added when appropriate:

Cookie cookie = new Cookie("testCookie", "12345");

driver.manage().addCookie(cookie);


25. Implicit Wait

An implicit wait tells WebDriver to wait for a specified amount of time when attempting to find elements before throwing a not-found exception.

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

Implicit waits should be used carefully, particularly when a project also relies heavily on explicit waits.


26. Explicit Wait

Explicit waits are useful when a particular condition must become true before continuing.

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement loginButton = wait.until(

    ExpectedConditions.elementToBeClickable(By.id("login"))

);

 

loginButton.click();


27. Common ExpectedConditions

ConditionPurpose
visibilityOfElementLocated()Waits until an element is visible.
elementToBeClickable()Waits until an element can be clicked.
presenceOfElementLocated()Waits until an element is present in the DOM.
presenceOfAllElementsLocatedBy()Waits for multiple elements to be present.
alertIsPresent()Waits for an alert.
titleContains()Waits until the title contains specific text.
urlContains()Waits until the URL contains specific text.


28. Handling Alerts

JavaScript alerts can be handled using switchTo().alert().

Alert alert = driver.switchTo().alert();

 

String message = alert.getText();

System.out.println(message);

 

alert.accept();

Other common operations include:

alert.dismiss();

 

String text = alert.getText();

 

alert.sendKeys("Test");


29. Handling Frames

If an element is located inside an iframe, Selenium must switch into that frame before interacting with the element.

driver.switchTo().frame("paymentFrame");

 

WebElement cardNumber = driver.findElement(By.id("cardNumber"));

cardNumber.sendKeys("1234567890");

 

driver.switchTo().defaultContent();

Explicit waiting can also be used when the frame is loaded dynamically.

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

 

wait.until(

    ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("paymentFrame"))

);


30. Handling Multiple Browser Windows

Selenium provides window handles for identifying browser windows or tabs.

String parentWindow = driver.getWindowHandle();

 

Set<String> windows = driver.getWindowHandles();

 

for (String window : windows) {

    if (!window.equals(parentWindow)) {

        driver.switchTo().window(window);

    }

}

After completing the work in the child window, the script can switch back to the parent window.

driver.switchTo().window(parentWindow);


31. Taking Screenshots

Screenshots are useful for debugging and test reporting.

File screenshot = ((TakesScreenshot) driver)

        .getScreenshotAs(OutputType.FILE);

 

Files.copy(

        screenshot.toPath(),

        Path.of("screenshot.png"),

        StandardCopyOption.REPLACE_EXISTING

);


32. JavaScript Execution

Selenium provides JavascriptExecutor for executing JavaScript in the browser when a normal WebDriver interaction is not appropriate for a specific task.

JavascriptExecutor js = (JavascriptExecutor) driver;

 

js.executeScript("window.scrollTo(0, document.body.scrollHeight);");

JavaScript execution should not replace normal WebDriver interactions unnecessarily. Prefer standard WebDriver APIs whenever they can perform the required operation reliably.


33. Handling Dropdowns

For standard HTML <select> elements, Selenium provides the Select class.

WebElement countryElement = driver.findElement(By.id("country"));

 

Select country = new Select(countryElement);

 

country.selectByVisibleText("India");

Other selection methods include:

country.selectByValue("IN");

country.selectByIndex(1);


34. Mouse and Keyboard Actions

The Selenium Actions API can be used for advanced user interactions such as hover, drag-and-drop, double-click, right-click, and keyboard combinations.

Actions actions = new Actions(driver);

 

WebElement menu = driver.findElement(By.id("menu"));

 

actions.moveToElement(menu).perform();

Double-click:

actions.doubleClick(element).perform();

Right-click:

actions.contextClick(element).perform();


35. Keyboard Actions

WebElement searchBox = driver.findElement(By.id("search"));

 

searchBox.sendKeys("Selenium");

 

Actions actions = new Actions(driver);

actions.keyDown(Keys.CONTROL)

       .sendKeys("a")

       .keyUp(Keys.CONTROL)

       .perform();


36. Closing the Browser

close() closes the current browser window.

driver.close();

quit() ends the WebDriver session and closes the associated browser windows.

driver.quit();

For complete test cleanup, quit() is generally preferred at the end of a test or test suite.


37. First WebDriver with Java Program

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class FirstWebDriverTest {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

 

        try {

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

 

            String title = driver.getTitle();

            String url = driver.getCurrentUrl();

 

            System.out.println("Title: " + title);

            System.out.println("URL: " + url);

        } finally {

            driver.quit();

        }

    }

}


38. Complete Form Automation Example

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class FormAutomation {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

 

        try {

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

 

            WebElement username = driver.findElement(By.id("username"));

            WebElement password = driver.findElement(By.id("password"));

            WebElement loginButton = driver.findElement(By.id("login"));

 

            username.sendKeys("admin");

            password.sendKeys("admin123");

            loginButton.click();

 

            System.out.println("Login action completed");

        } finally {

            driver.quit();

        }

    }

}


39. Verifying Page Title

Assertions can be used in a test framework to verify expected results.

String actualTitle = driver.getTitle();

 

if (actualTitle.equals("Expected Title")) {

    System.out.println("Title validation passed");

} else {

    System.out.println("Title validation failed");

}

In a real test framework, assertions from TestNG or JUnit are generally preferred.


40. WebDriver with TestNG

TestNG can be used to organize Selenium tests, setup and teardown browser sessions, group tests, parameterize tests, and generate test results.

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.Test;

 

public class LoginTest {

    WebDriver driver;

 

    @BeforeMethod

    public void setUp() {

        driver = new ChromeDriver();

    }

 

    @Test

    public void verifyHomePage() {

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

 

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

    }

 

    @AfterMethod

    public void tearDown() {

        driver.quit();

    }

}


41. WebDriver with JUnit

JUnit is another popular Java testing framework that can be combined with Selenium WebDriver.

import org.junit.jupiter.api.AfterEach;

import org.junit.jupiter.api.BeforeEach;

import org.junit.jupiter.api.Test;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class HomePageTest {

    private WebDriver driver;

 

    @BeforeEach

    void setUp() {

        driver = new ChromeDriver();

    }

 

    @Test

    void verifyTitle() {

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

 

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

    }

 

    @AfterEach

    void tearDown() {

        driver.quit();

    }

}


42. WebDriver and Page Object Model

Page Object Model (POM) is a design pattern commonly used in Selenium frameworks. Each important page or component is represented by a Java class containing its locators and user interactions.

LoginPage

    |

    +-- usernameField

    +-- passwordField

    +-- loginButton

    |

    +-- enterUsername()

    +-- enterPassword()

    +-- clickLogin()

Example:

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

 

public class LoginPage {

    private WebDriver driver;

 

    private By username = By.id("username");

    private By password = By.id("password");

    private By loginButton = By.id("login");

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void enterUsername(String value) {

        driver.findElement(username).sendKeys(value);

    }

 

    public void enterPassword(String value) {

        driver.findElement(password).sendKeys(value);

    }

 

    public void clickLogin() {

        driver.findElement(loginButton).click();

    }

}


43. Advantages of Page Object Model

  • Improves code organization.
  • Reduces duplication.
  • Makes locator maintenance easier.
  • Separates page behavior from test logic.
  • Improves framework scalability.
  • Supports reusable page methods.


44. WebDriver and Data-Driven Testing

Data-driven testing separates test data from automation logic. The same Selenium test can execute with different usernames, passwords, search values, or other inputs.

String username = "admin";

String password = "admin123";

 

driver.findElement(By.id("username")).sendKeys(username);

driver.findElement(By.id("password")).sendKeys(password);

In larger frameworks, test data may come from CSV files, Excel files, JSON, databases, or TestNG data providers.


45. WebDriver and Cross-Browser Testing

The WebDriver interface allows tests to be written against a common API while different browser-specific implementations are used for different browsers.

WebDriver chrome = new ChromeDriver();

WebDriver firefox = new FirefoxDriver();

WebDriver edge = new EdgeDriver();

BrowserCommon Java Driver
Google ChromeChromeDriver
Mozilla FirefoxFirefoxDriver
Microsoft EdgeEdgeDriver


46. Browser Options

Browser-specific options can be used to configure how the browser starts.

ChromeOptions options = new ChromeOptions();

 

options.addArguments("--start-maximized");

 

WebDriver driver = new ChromeDriver(options);

For headless execution:

ChromeOptions options = new ChromeOptions();

options.addArguments("--headless=new");

 

WebDriver driver = new ChromeDriver(options);


47. Headless Browser Testing

Headless execution runs the browser without displaying the normal browser user interface. It is useful in CI/CD environments and server-based test execution.

ChromeOptions options = new ChromeOptions();

options.addArguments("--headless=new");

 

WebDriver driver = new ChromeDriver(options);

 

try {

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

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

} finally {

    driver.quit();

}


48. WebDriver and Selenium Grid

Selenium Grid can be used when tests need to run on remote machines, different browsers, or multiple environments. A Java Selenium test can connect to a remote WebDriver endpoint rather than launching a local browser directly.

URL gridUrl = new URL("http://localhost:4444");

 

WebDriver driver = new RemoteWebDriver(

    gridUrl,

    new ChromeOptions()

);


49. WebDriver in CI/CD

Selenium Java tests can be executed through CI/CD systems such as Jenkins, GitHub Actions, GitLab CI, and other automation platforms. A typical pipeline can compile the Maven project and execute Selenium tests.

Source Code

    |

    v

CI/CD Pipeline

    |

    v

Maven Build

    |

    v

Selenium Tests

    |

    v

Browser

    |

    v

Test Results / Reports


50. WebDriver Exception Handling

Selenium automation can encounter exceptions such as element-not-found, timeout, stale element, invalid selector, or browser/session-related errors.

try {

    WebElement login = driver.findElement(By.id("login"));

    login.click();

} catch (Exception e) {

    System.out.println("Automation error: " + e.getMessage());

} finally {

    driver.quit();

}

In production frameworks, specific Selenium exceptions should generally be handled where meaningful rather than catching every exception indiscriminately.


51. Common Selenium Exceptions

ExceptionTypical Cause
NoSuchElementExceptionElement could not be found using the supplied locator.
TimeoutExceptionExpected wait condition was not satisfied within the timeout.
StaleElementReferenceExceptionThe referenced DOM element is no longer attached to the current page DOM.
ElementClickInterceptedExceptionAnother element prevents the target from being clicked.
InvalidSelectorExceptionLocator syntax is invalid.
NoSuchFrameExceptionRequested frame could not be found.
NoSuchWindowExceptionRequested browser window no longer exists.
WebDriverExceptionGeneral WebDriver-related failure.


52. Common WebDriver Mistakes

  • Using unstable locators.
  • Using hard-coded sleeps everywhere.
  • Not waiting for dynamic elements.
  • Forgetting to close browser sessions.
  • Mixing incompatible dependencies.
  • Creating duplicated page interaction code.
  • Using JavaScript when a normal WebDriver operation would work.
  • Ignoring screenshots and logs when diagnosing failures.
  • Hard-coding environment-specific values.


53. Best Practices for WebDriver with Java

  1. Use stable and meaningful locators.
  2. Prefer explicit waits for specific dynamic conditions.
  3. Keep test data separate from test logic.
  4. Use Page Object Model for larger projects.
  5. Use Maven for dependency management.
  6. Use TestNG or JUnit for structured test execution.
  7. Always clean up WebDriver sessions.
  8. Capture useful logs and screenshots for failures.
  9. Keep browser configuration centralized.
  10. Avoid unnecessary Thread.sleep() calls.
  11. Design tests to be independent whenever possible.
  12. Run tests in multiple browsers when cross-browser coverage is required.


54. Practical Project: Login Automation

Consider a web application containing a login page with username, password, and login button.

import java.time.Duration;

 

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.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;

 

public class LoginAutomation {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

 

        try {

            driver.manage().window().maximize();

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

 

            WebDriverWait wait =

                new WebDriverWait(driver, Duration.ofSeconds(10));

 

            WebElement username =

                wait.until(ExpectedConditions.visibilityOfElementLocated(

                    By.id("username")

                ));

 

            WebElement password =

                driver.findElement(By.id("password"));

 

            WebElement loginButton =

                driver.findElement(By.id("login"));

 

            username.sendKeys("admin");

            password.sendKeys("admin123");

            loginButton.click();

 

            System.out.println("Login test executed");

        } finally {

            driver.quit();

        }

    }

}


55. Practical Selenium Automation Flow

Start Test

    |

    v

Create WebDriver

    |

    v

Configure Browser

    |

    v

Open Application

    |

    v

Locate Web Elements

    |

    v

Enter Test Data

    |

    v

Perform Actions

    |

    v

Wait for Application State

    |

    v

Validate Result

    |

    v

Capture Evidence if Required

    |

    v

Quit WebDriver

    |

    v

End Test


56. WebDriver Test Framework Structure

selenium-framework/

├── pom.xml

├── src/

│   ├── main/

│   │   └── java/

│   │       ├── pages/

│   │       ├── utilities/

│   │       └── base/

│   └── test/

│       └── java/

│           └── tests/

└── test-data/

    ├── users.json

    └── testdata.csv


57. WebDriver and Assertions

Assertions verify whether the actual application behavior matches the expected result.

Example using TestNG:

import static org.testng.Assert.assertEquals;

 

String actualTitle = driver.getTitle();

 

assertEquals(actualTitle, "Expected Title");

Assertions should validate meaningful business or UI outcomes instead of merely confirming that commands executed without exceptions.


58. WebDriver and Maven Commands

mvn -version

mvn clean

mvn compile

mvn test

mvn clean test

mvn package

mvn dependency:tree

These commands are useful for building and executing Selenium Java Maven projects.


59. WebDriver and Debugging

When a Selenium test fails, check the following:

  • Is the browser installed and accessible?
  • Is the Selenium dependency available?
  • Is the locator correct?
  • Is the page fully loaded?
  • Is the element inside an iframe?
  • Is the element located in another window or tab?
  • Is the element dynamically rendered?
  • Is an explicit wait required?
  • Did the DOM change after the element was located?
  • Are browser and Selenium components compatible?


60. WebDriver Interview Questions

Q1. What is Selenium WebDriver?

Selenium WebDriver is an API and browser automation technology used to programmatically control supported web browsers.

Q2. What is WebDriver in Java?

WebDriver is the primary Selenium Java interface used to control browser sessions and interact with web applications.

Q3. What is the difference between WebDriver and ChromeDriver?

WebDriver is the common Selenium interface, while ChromeDriver is a browser-specific implementation used to control Chrome.

Q4. What is WebElement?

WebElement represents an element in the web page DOM and provides methods such as click(), sendKeys(), clear(), and getText().

Q5. What is the use of By?

By provides locator strategies such as ID, name, CSS selector, XPath, and class name.

Q6. What is the difference between close() and quit()?

close() closes the current browser window, while quit() ends the WebDriver session and closes its associated windows.

Q7. What is an explicit wait?

An explicit wait waits for a specific condition to become true before continuing the test.

Q8. Why is Page Object Model used?

POM separates page-specific locators and actions from test logic, improving maintainability and reuse.

Q9. How can Selenium handle multiple windows?

Selenium provides window handles through getWindowHandle() and getWindowHandles(), followed by switchTo().window().

Q10. How can Selenium handle frames?

The driver can switch into a frame using switchTo().frame() and return to the main document using switchTo().defaultContent().


61. Quick Revision Table

TaskJava Selenium Code
Create Chrome sessionnew ChromeDriver()
Open URLdriver.get("URL")
Find elementdriver.findElement(By.id("x"))
Find multiple elementsdriver.findElements(By.tagName("a"))
Enter textelement.sendKeys("text")
Clickelement.click()
Read textelement.getText()
Get titledriver.getTitle()
Get URLdriver.getCurrentUrl()
Go backdriver.navigate().back()
Refreshdriver.navigate().refresh()
Maximizedriver.manage().window().maximize()
Explicit waitnew WebDriverWait(driver, Duration.ofSeconds(10))
Switch to alertdriver.switchTo().alert()
Switch to framedriver.switchTo().frame(...)
Switch windowdriver.switchTo().window(...)
Close sessiondriver.quit()


62. Complete WebDriver with Java Example

import java.time.Duration;

 

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.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;

 

public class CompleteWebDriverExample {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        try {

            driver.manage().window().maximize();

 

            driver.get("https://www.selenium.dev/selenium/web/web-form.html");

 

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

            System.out.println("URL: " + driver.getCurrentUrl());

 

            WebDriverWait wait =

                new WebDriverWait(driver, Duration.ofSeconds(10));

 

            WebElement textBox =

                wait.until(ExpectedConditions.visibilityOfElementLocated(

                    By.name("my-text")

                ));

 

            WebElement submitButton =

                driver.findElement(By.cssSelector("button"));

 

            textBox.sendKeys("Selenium with Java");

            submitButton.click();

 

            WebElement message =

                wait.until(ExpectedConditions.visibilityOfElementLocated(

                    By.id("message")

                ));

 

            System.out.println("Message: " + message.getText());

 

        } finally {

            driver.quit();

        }

    }

}


63. Real-World Applications of WebDriver with Java

  • Login and logout testing.
  • E-commerce checkout testing.
  • Registration form testing.
  • Search functionality testing.
  • Shopping cart validation.
  • Banking application UI testing.
  • Enterprise application regression testing.
  • Cross-browser testing.
  • Smoke and sanity testing.
  • Regression test automation.
  • CI/CD browser test execution.
  • End-to-end web application testing.


64. WebDriver Automation Best-Practice Flow

Requirement

    |

    v

Identify Test Scenario

    |

    v

Create Selenium Java Project

    |

    v

Configure Maven

    |

    v

Create WebDriver

    |

    v

Open Application

    |

    v

Identify Stable Locators

    |

    v

Create Page Objects

    |

    v

Add Explicit Waits

    |

    v

Perform Browser Actions

    |

    v

Validate Expected Results

    |

    v

Capture Logs / Screenshots

    |

    v

Generate Test Report

    |

    v

Execute Through CI/CD


65. Summary

Selenium WebDriver with Java provides a powerful way to automate web browsers and validate web applications. The WebDriver interface provides browser-level operations, while WebElement is used to interact with individual elements.

A strong Selenium Java implementation combines stable locators, appropriate waits, reusable page objects, test frameworks such as TestNG or JUnit, Maven dependency management, browser configuration, assertions, screenshots, and structured reporting. These practices help transform individual Selenium scripts into maintainable automation frameworks.


66. Course Resources

Learn more about Selenium and WebDriver with Java through the following resources:

whatsapp