Skip to content
CodeKruPro

Automation tool (Selenium) · Java

Selenium basics and browser control

WebDriver architecture, starting a browser, navigation and closing it.

Learn: Selenium basics in Java: how WebDriver works and controls the browser7 minute read

Selenium is a free, open-source tool (its code is public and anyone can use it) that controls a real web browser from code. Your test tells the browser what to do (open a page, click, type), and Selenium carries out each step. Almost every automation interview starts here, because everything else (locators, waits, frameworks) builds on it. The interviewer wants to see three things: you know what Selenium is and is not, you can explain how a command reaches the browser, and you can open and close a browser cleanly. This page covers Selenium 4 on Java 21.

What Selenium is made of

WebDriver is the API you call from your Java code. Selenium Grid runs browsers on other machines, so many tests can run at the same time. Selenium IDE is a browser extension that records and plays back clicks. Selenium Manager, included since version 4.6, finds or downloads the right browser driver for you.

Selenium is not a test framework. It has no assertions (checks that fail the test when a result is wrong, such as "the title must be Home"), no reports and no way to group tests. You pair it with a test runner such as TestNG or JUnit 5 (a library that finds your tests, runs them and shows the results), and a build tool such as Maven (a tool that builds your project and downloads libraries).

How a command reaches the browser

Take driver.findElement(By.id("user")). Four parts work together:

  1. The Selenium Java library (the client library, also called the language binding) turns the call into an HTTP request with a JSON body. HTTP is the way programs send requests over a network, and JSON is a plain-text format for data.
  2. The request follows the W3C WebDriver protocol. W3C is the body that writes web standards, and this protocol is the official way to control a browser. Selenium 4 sends its normal commands (find an element, click, type, read text) with this protocol. A few extra features, such as DevTools access (Chrome DevTools Protocol) and event listening (WebDriver BiDi), use a separate connection that stays open next to it.
  3. A browser driver receives the request. It is a small server program: chromedriver for Chrome, geckodriver for Firefox, msedgedriver for Edge.
  4. The driver tells the browser what to do and sends back a JSON response, for example an id for the element it found.
The test calls the client library, which sends an HTTP request to the browser driver, which drives the browser; responses come back the same way, optionally through Selenium Grid.
Every Selenium command is one request and one response.

So findElement is one round trip and the click() after it is another. That is why good locators and well-placed waits matter: each extra lookup costs time.

WebDriver is an interface

An interface in Java lists methods without code; classes then provide the code. WebDriver is an interface. ChromeDriver extends ChromiumDriver, which extends RemoteWebDriver, the class that sends the HTTP calls. RemoteWebDriver also implements other interfaces such as JavascriptExecutor and TakesScreenshot. That is why you cast the driver to use those features: a cast tells Java to treat the object as that other type, for example ((TakesScreenshot) driver).

You declare the variable with the interface type, so the rest of the code does not care which browser it gets. A driver factory can later return Firefox, Edge or a RemoteWebDriver for Grid, and no test changes.

A first script, step by step

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

public class FirstScript {
    public static void main(String[] args) {
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--headless=new", "--window-size=1920,1080");
        WebDriver driver = new ChromeDriver(options);
        try {
            driver.get("https://example.com");
            System.out.println(driver.getTitle());
        } finally {
            driver.quit();
        }
    }
}
  1. Create the browser settings with an options class (ChromeOptions, FirefoxOptions). Headless means the browser runs without a visible window, which is normal on build servers (machines that run your tests automatically, with no screen).
  2. Set a window size. The default headless window is small, and responsive pages may hide menus.
  3. Start the browser. Selenium Manager finds the driver if none is set up.
  4. get() opens the page and waits until it has loaded.
  5. Call quit() in a finally block, so a failure never leaves a browser running. A finally block runs whether or not an error happened in the try block above it.

Navigation and page details

driver.navigate().to(url) loads a page the same way as get(). The difference is only that navigate() also gives you back(), forward() and refresh(). Both add to the browser history. getTitle(), getCurrentUrl() and getPageSource() read the page. driver.manage().window().setSize(new Dimension(1024, 768)) sets the window size.

close() versus quit()

close() closes only the current window. If other windows are open, the session goes on, and you must switch to one of them before the next command. quit() closes every window, ends the session and stops the driver process.

How to answer in an interview

For "What is Selenium?", give one sentence of definition, name the parts, then one strength and one limit. For "Explain the architecture", walk the four parts in order and end with "each command is one HTTP round trip". If asked what changed in Selenium 4, mention the W3C WebDriver protocol (it replaced the old JSON Wire protocol), relative locators, switchTo().newWindow(), Duration timeouts and Selenium Manager.

Common mistakes

  • Calling Selenium a testing framework. It only drives the browser.
  • Saying navigate().to() keeps history and get() does not. Both add to history.
  • Using close() in teardown (the clean-up step after each test). Use quit().
  • Forgetting the limits: Selenium cannot see operating system dialogs (windows opened by Windows or macOS, not by the web page), solve CAPTCHAs (the "prove you are human" puzzles) or test native mobile apps (apps installed on a phone; Appium does that).

Recap

Selenium drives real browsers, sending normal commands through the W3C WebDriver protocol. Your code talks to a client library, the library talks HTTP to a driver, and the driver controls the browser. Code against the WebDriver interface, configure the browser with an options class, and always end with quit().

13 questions0/13 solved

StatusQuestionDifficultyAsked in
Not startedOpen a browser, open a page and print its titleEasyAsked in: Accenture, Capgemini, Infosys +3
Not startedWhat is Selenium? Parts, strengths and limitsEasyAsked in: Accenture, Infosys, TCS +1
Not startedVisit two pages one after anotherEasyAsked in: Accenture, Infosys, TCS +1
Not startedGo back and forward in the browser historyEasyAsked in: Accenture, Infosys, TCS +1
Pro+What kind of type is WebDriver in Java?EasyAsked in: Accenture, Infosys, Wipro
Pro+close() versus quit()EasyAsked in: Accenture, TCS, Wipro
Pro+Chrome is installed but there is no chromedriver. What happens?Easy-MediumAsked in: Accenture, Infosys, Wipro
Pro+Selenium WebDriver architecture in JavaMediumAsked in: Accenture, Infosys, Wipro
Pro+What changed in Selenium 4 (Java)?MediumAsked in: Accenture, Infosys, Wipro
Pro+driver.get() versus driver.navigate().to()EasyAsked in: Accenture, Infosys, TCS +1
Pro+Start Chrome headless with a fixed window size (Java)Easy-MediumAsked in: Capgemini, Cognizant, Infosys +1
Not startedSet the browser window size and read it backEasy
Not startedRead the page source and search itEasy
Not startedNot startedIn progressIn progressSolvedSolvedPro+Pro+

The first 2 questions of each topic are free. Pro+ opens every question.

Back to the plan