Popular Searches
Popular Course Categories
Popular Courses

WebDriver with Java

Selenium with Java

<div class="selenium-notes">

<h1>WebDriver with Java</h1>

<p><strong>WebDriver with Java</strong> 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.</p>

<p>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.</p>

<p><strong>Course Resources:</strong> <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Selenium Training</a> | <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a></p>

<hr>

<h2>1. What is WebDriver?</h2>

<p>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.</p>

<p>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.</p>

<pre><code>Java Selenium Program

        |

        v

Selenium WebDriver API

        |

        v

Browser Driver

        |

        v

Web Browser

        |

        v

Web Application</code></pre>

<hr>

<h2>2. Why Use WebDriver with Java?</h2>

<ul>

<li>Java is widely used for enterprise application development and test automation.</li>

<li>Selenium provides a mature Java API for browser automation.</li>

<li>Java works well with TestNG and JUnit.</li>

<li>Maven can manage Selenium and testing dependencies.</li>

<li>Java supports object-oriented automation frameworks.</li>

<li>Java Selenium projects can be integrated with CI/CD tools.</li>

<li>Java is suitable for implementing Page Object Model and reusable automation components.</li>

</ul>

<hr>

<h2>3. Important Components of Selenium WebDriver</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Component</th><th>Purpose</th></tr>

<tr><td>WebDriver</td><td>Controls the browser and provides browser-level operations.</td></tr>

<tr><td>WebElement</td><td>Represents an element present on a web page.</td></tr>

<tr><td>By</td><td>Provides locator strategies for finding elements.</td></tr>

<tr><td>ChromeDriver</td><td>Controls Google Chrome.</td></tr>

<tr><td>FirefoxDriver</td><td>Controls Mozilla Firefox.</td></tr>

<tr><td>EdgeDriver</td><td>Controls Microsoft Edge.</td></tr>

<tr><td>WebDriverWait</td><td>Provides explicit waiting functionality.</td></tr>

<tr><td>ExpectedConditions</td><td>Provides predefined conditions for explicit waits.</td></tr>

</table>

<hr>

<h2>4. Selenium WebDriver Architecture</h2>

<p>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.</p>

<pre><code>Java Automation Test

        |

        v

Selenium Java Bindings

        |

        v

WebDriver API

        |

        v

ChromeDriver / FirefoxDriver / EdgeDriver

        |

        v

Chrome / Firefox / Edge

        |

        v

Web Application</code></pre>

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

<hr>

<h2>5. Prerequisites for WebDriver with Java</h2>

<p>Before creating a Java Selenium project, install and configure the required development tools.</p>

<ul>

<li>Java Development Kit (JDK)</li>

<li>Java IDE such as IntelliJ IDEA or Eclipse</li>

<li>Maven, when using a Maven project</li>

<li>A supported web browser</li>

<li>Selenium Java dependency</li>

</ul>

<p>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.</p>

<hr>

<h2>6. Creating a Maven Project</h2>

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

<p>A typical Selenium Maven project contains the following structure:</p>

<pre><code>selenium-java-project/

├── pom.xml

└── src/

    ├── main/

    │   └── java/

    └── test/

        └── java/

            └── tests/</code></pre>

<hr>

<h2>7. Selenium Java Maven Dependency</h2>

<p>The Selenium Java library can be added to a Maven project through the <code>selenium-java</code> artifact.</p>

<pre><code>&lt;dependency&gt;

    &lt;groupId&gt;org.seleniumhq.selenium&lt;/groupId&gt;

    &lt;artifactId&gt;selenium-java&lt;/artifactId&gt;

    &lt;version&gt;YOUR_SELENIUM_VERSION&lt;/version&gt;

&lt;/dependency&gt;</code></pre>

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

<hr>

<h2>8. Important Java Selenium Imports</h2>

<pre><code>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;</code></pre>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Import</th><th>Purpose</th></tr>

<tr><td>WebDriver</td><td>Provides the main browser-control interface.</td></tr>

<tr><td>ChromeDriver</td><td>Creates a Chrome browser session.</td></tr>

<tr><td>WebElement</td><td>Represents an HTML element.</td></tr>

<tr><td>By</td><td>Provides locator strategies.</td></tr>

<tr><td>WebDriverWait</td><td>Creates an explicit wait.</td></tr>

<tr><td>ExpectedConditions</td><td>Provides wait conditions.</td></tr>

<tr><td>Duration</td><td>Defines wait durations.</td></tr>

</table>

<hr>

<h2>9. Creating a WebDriver Object</h2>

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

<pre><code>WebDriver driver = new ChromeDriver();</code></pre>

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

<hr>

<h2>10. Launching the Browser</h2>

<pre><code>WebDriver driver = new ChromeDriver();</code></pre>

<p>This creates a Chrome browser session. The browser driver handles communication between Selenium and the browser.</p>

<hr>

<h2>11. Opening a Website</h2>

<p>The <code>get()</code> method navigates the browser to a specified URL.</p>

<pre><code>driver.get("https://example.com");</code></pre>

<p>Another navigation approach is:</p>

<pre><code>driver.navigate().to("https://example.com");</code></pre>

<hr>

<h2>12. Difference Between get() and navigate().to()</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Method</th><th>Purpose</th></tr>

<tr><td>get()</td><td>Loads a specified URL.</td></tr>

<tr><td>navigate().to()</td><td>Navigates to a specified URL through the navigation interface.</td></tr>

<tr><td>navigate().back()</td><td>Moves back in browser history.</td></tr>

<tr><td>navigate().forward()</td><td>Moves forward in browser history.</td></tr>

<tr><td>navigate().refresh()</td><td>Refreshes the current page.</td></tr>

</table>

<hr>

<h2>13. Getting the Page Title</h2>

<p>The <code>getTitle()</code> method returns the title of the current web page.</p>

<pre><code>String title = driver.getTitle();

System.out.println(title);</code></pre>

<hr>

<h2>14. Getting the Current URL</h2>

<pre><code>String currentUrl = driver.getCurrentUrl();

System.out.println(currentUrl);</code></pre>

<p>This is useful when validating redirects and navigation behavior.</p>

<hr>

<h2>15. Finding Web Elements</h2>

<p>Most Selenium operations begin by locating an element. Selenium Java provides the <code>findElement()</code> method for locating a single element.</p>

<pre><code>WebElement username = driver.findElement(By.id("username"));</code></pre>

<p>For multiple matching elements, use <code>findElements()</code>.</p>

<pre><code>List&lt;WebElement&gt; links = driver.findElements(By.tagName("a"));</code></pre>

<hr>

<h2>16. Selenium Locators</h2>

<p>Locators tell Selenium which element should be interacted with.</p>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Locator</th><th>Java Syntax</th></tr>

<tr><td>ID</td><td><code>By.id("username")</code></td></tr>

<tr><td>Name</td><td><code>By.name("email")</code></td></tr>

<tr><td>Class Name</td><td><code>By.className("login-button")</code></td></tr>

<tr><td>Tag Name</td><td><code>By.tagName("button")</code></td></tr>

<tr><td>Link Text</td><td><code>By.linkText("Login")</code></td></tr>

<tr><td>Partial Link Text</td><td><code>By.partialLinkText("Log")</code></td></tr>

<tr><td>CSS Selector</td><td><code>By.cssSelector("#username")</code></td></tr>

<tr><td>XPath</td><td><code>By.xpath("//input[@id='username']")</code></td></tr>

</table>

<hr>

<h2>17. WebElement in Selenium Java</h2>

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

<pre><code>WebElement username = driver.findElement(By.id("username"));

 

username.sendKeys("admin");

username.clear();

username.click();

 

String value = username.getAttribute("value");</code></pre>

<hr>

<h2>18. Common WebElement Methods</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Method</th><th>Purpose</th></tr>

<tr><td>click()</td><td>Clicks an element.</td></tr>

<tr><td>sendKeys()</td><td>Enters text or keyboard input.</td></tr>

<tr><td>clear()</td><td>Clears an editable field.</td></tr>

<tr><td>getText()</td><td>Returns visible text.</td></tr>

<tr><td>getAttribute()</td><td>Returns an element attribute.</td></tr>

<tr><td>isDisplayed()</td><td>Checks whether an element is displayed.</td></tr>

<tr><td>isEnabled()</td><td>Checks whether an element is enabled.</td></tr>

<tr><td>isSelected()</td><td>Checks whether a selectable element is selected.</td></tr>

</table>

<hr>

<h2>19. Entering Data into a Text Box</h2>

<pre><code>WebElement username = driver.findElement(By.id("username"));

username.sendKeys("admin");</code></pre>

<p>For password fields:</p>

<pre><code>WebElement password = driver.findElement(By.id("password"));

password.sendKeys("admin123");</code></pre>

<hr>

<h2>20. Clicking a Button</h2>

<pre><code>WebElement loginButton = driver.findElement(By.id("login"));

loginButton.click();</code></pre>

<p>Selenium first locates the button and then sends the click command to the browser.</p>

<hr>

<h2>21. Reading Text from a Web Page</h2>

<pre><code>WebElement message = driver.findElement(By.id("message"));

String text = message.getText();

 

System.out.println(text);</code></pre>

<p>This is commonly used for validation.</p>

<hr>

<h2>22. Browser Navigation</h2>

<pre><code>driver.get("https://example.com");

 

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

driver.navigate().back();

driver.navigate().forward();

driver.navigate().refresh();</code></pre>

<hr>

<h2>23. Managing Browser Window</h2>

<p>Selenium provides methods for maximizing, minimizing, fullscreen mode, and controlling window size.</p>

<pre><code>driver.manage().window().maximize();

driver.manage().window().fullscreen();</code></pre>

<p>For a specific window size:</p>

<pre><code>driver.manage().window().setSize(new Dimension(1280, 720));</code></pre>

<hr>

<h2>24. Browser Cookies</h2>

<p>Selenium can interact with cookies through the WebDriver cookie API.</p>

<pre><code>driver.manage().deleteAllCookies();</code></pre>

<p>A cookie can also be added when appropriate:</p>

<pre><code>Cookie cookie = new Cookie("testCookie", "12345");

driver.manage().addCookie(cookie);</code></pre>

<hr>

<h2>25. Implicit Wait</h2>

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

<pre><code>driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));</code></pre>

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

<hr>

<h2>26. Explicit Wait</h2>

<p>Explicit waits are useful when a particular condition must become true before continuing.</p>

<pre><code>WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement loginButton = wait.until(

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

);

 

loginButton.click();</code></pre>

<hr>

<h2>27. Common ExpectedConditions</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Condition</th><th>Purpose</th></tr>

<tr><td>visibilityOfElementLocated()</td><td>Waits until an element is visible.</td></tr>

<tr><td>elementToBeClickable()</td><td>Waits until an element can be clicked.</td></tr>

<tr><td>presenceOfElementLocated()</td><td>Waits until an element is present in the DOM.</td></tr>

<tr><td>presenceOfAllElementsLocatedBy()</td><td>Waits for multiple elements to be present.</td></tr>

<tr><td>alertIsPresent()</td><td>Waits for an alert.</td></tr>

<tr><td>titleContains()</td><td>Waits until the title contains specific text.</td></tr>

<tr><td>urlContains()</td><td>Waits until the URL contains specific text.</td></tr>

</table>

<hr>

<h2>28. Handling Alerts</h2>

<p>JavaScript alerts can be handled using <code>switchTo().alert()</code>.</p>

<pre><code>Alert alert = driver.switchTo().alert();

 

String message = alert.getText();

System.out.println(message);

 

alert.accept();</code></pre>

<p>Other common operations include:</p>

<pre><code>alert.dismiss();

 

String text = alert.getText();

 

alert.sendKeys("Test");</code></pre>

<hr>

<h2>29. Handling Frames</h2>

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

<pre><code>driver.switchTo().frame("paymentFrame");

 

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

cardNumber.sendKeys("1234567890");

 

driver.switchTo().defaultContent();</code></pre>

<p>Explicit waiting can also be used when the frame is loaded dynamically.</p>

<pre><code>WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

 

wait.until(

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

);</code></pre>

<hr>

<h2>30. Handling Multiple Browser Windows</h2>

<p>Selenium provides window handles for identifying browser windows or tabs.</p>

<pre><code>String parentWindow = driver.getWindowHandle();

 

Set&lt;String&gt; windows = driver.getWindowHandles();

 

for (String window : windows) {

    if (!window.equals(parentWindow)) {

        driver.switchTo().window(window);

    }

}</code></pre>

<p>After completing the work in the child window, the script can switch back to the parent window.</p>

<pre><code>driver.switchTo().window(parentWindow);</code></pre>

<hr>

<h2>31. Taking Screenshots</h2>

<p>Screenshots are useful for debugging and test reporting.</p>

<pre><code>File screenshot = ((TakesScreenshot) driver)

        .getScreenshotAs(OutputType.FILE);

 

Files.copy(

        screenshot.toPath(),

        Path.of("screenshot.png"),

        StandardCopyOption.REPLACE_EXISTING

);</code></pre>

<hr>

<h2>32. JavaScript Execution</h2>

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

<pre><code>JavascriptExecutor js = (JavascriptExecutor) driver;

 

js.executeScript("window.scrollTo(0, document.body.scrollHeight);");</code></pre>

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

<hr>

<h2>33. Handling Dropdowns</h2>

<p>For standard HTML <code>&lt;select&gt;</code> elements, Selenium provides the <code>Select</code> class.</p>

<pre><code>WebElement countryElement = driver.findElement(By.id("country"));

 

Select country = new Select(countryElement);

 

country.selectByVisibleText("India");</code></pre>

<p>Other selection methods include:</p>

<pre><code>country.selectByValue("IN");

country.selectByIndex(1);</code></pre>

<hr>

<h2>34. Mouse and Keyboard Actions</h2>

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

<pre><code>Actions actions = new Actions(driver);

 

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

 

actions.moveToElement(menu).perform();</code></pre>

<p>Double-click:</p>

<pre><code>actions.doubleClick(element).perform();</code></pre>

<p>Right-click:</p>

<pre><code>actions.contextClick(element).perform();</code></pre>

<hr>

<h2>35. Keyboard Actions</h2>

<pre><code>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();</code></pre>

<hr>

<h2>36. Closing the Browser</h2>

<p><code>close()</code> closes the current browser window.</p>

<pre><code>driver.close();</code></pre>

<p><code>quit()</code> ends the WebDriver session and closes the associated browser windows.</p>

<pre><code>driver.quit();</code></pre>

<p>For complete test cleanup, <code>quit()</code> is generally preferred at the end of a test or test suite.</p>

<hr>

<h2>37. First WebDriver with Java Program</h2>

<pre><code>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();

        }

    }

}</code></pre>

<hr>

<h2>38. Complete Form Automation Example</h2>

<pre><code>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();

        }

    }

}</code></pre>

<hr>

<h2>39. Verifying Page Title</h2>

<p>Assertions can be used in a test framework to verify expected results.</p>

<pre><code>String actualTitle = driver.getTitle();

 

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

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

} else {

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

}</code></pre>

<p>In a real test framework, assertions from TestNG or JUnit are generally preferred.</p>

<hr>

<h2>40. WebDriver with TestNG</h2>

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

<pre><code>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();

    }

}</code></pre>

<hr>

<h2>41. WebDriver with JUnit</h2>

<p>JUnit is another popular Java testing framework that can be combined with Selenium WebDriver.</p>

<pre><code>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();

    }

}</code></pre>

<hr>

<h2>42. WebDriver and Page Object Model</h2>

<p>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.</p>

<pre><code>LoginPage

    |

    +-- usernameField

    +-- passwordField

    +-- loginButton

    |

    +-- enterUsername()

    +-- enterPassword()

    +-- clickLogin()</code></pre>

<p>Example:</p>

<pre><code>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();

    }

}</code></pre>

<hr>

<h2>43. Advantages of Page Object Model</h2>

<ul>

<li>Improves code organization.</li>

<li>Reduces duplication.</li>

<li>Makes locator maintenance easier.</li>

<li>Separates page behavior from test logic.</li>

<li>Improves framework scalability.</li>

<li>Supports reusable page methods.</li>

</ul>

<hr>

<h2>44. WebDriver and Data-Driven Testing</h2>

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

<pre><code>String username = "admin";

String password = "admin123";

 

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

driver.findElement(By.id("password")).sendKeys(password);</code></pre>

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

<hr>

<h2>45. WebDriver and Cross-Browser Testing</h2>

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

<pre><code>WebDriver chrome = new ChromeDriver();

WebDriver firefox = new FirefoxDriver();

WebDriver edge = new EdgeDriver();</code></pre>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Browser</th><th>Common Java Driver</th></tr>

<tr><td>Google Chrome</td><td>ChromeDriver</td></tr>

<tr><td>Mozilla Firefox</td><td>FirefoxDriver</td></tr>

<tr><td>Microsoft Edge</td><td>EdgeDriver</td></tr>

</table>

<hr>

<h2>46. Browser Options</h2>

<p>Browser-specific options can be used to configure how the browser starts.</p>

<pre><code>ChromeOptions options = new ChromeOptions();

 

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

 

WebDriver driver = new ChromeDriver(options);</code></pre>

<p>For headless execution:</p>

<pre><code>ChromeOptions options = new ChromeOptions();

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

 

WebDriver driver = new ChromeDriver(options);</code></pre>

<hr>

<h2>47. Headless Browser Testing</h2>

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

<pre><code>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();

}</code></pre>

<hr>

<h2>48. WebDriver and Selenium Grid</h2>

<p>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.</p>

<pre><code>URL gridUrl = new URL("http://localhost:4444");

 

WebDriver driver = new RemoteWebDriver(

    gridUrl,

    new ChromeOptions()

);</code></pre>

<hr>

<h2>49. WebDriver in CI/CD</h2>

<p>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.</p>

<pre><code>Source Code

    |

    v

CI/CD Pipeline

    |

    v

Maven Build

    |

    v

Selenium Tests

    |

    v

Browser

    |

    v

Test Results / Reports</code></pre>

<hr>

<h2>50. WebDriver Exception Handling</h2>

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

<pre><code>try {

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

    login.click();

} catch (Exception e) {

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

} finally {

    driver.quit();

}</code></pre>

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

<hr>

<h2>51. Common Selenium Exceptions</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Exception</th><th>Typical Cause</th></tr>

<tr><td>NoSuchElementException</td><td>Element could not be found using the supplied locator.</td></tr>

<tr><td>TimeoutException</td><td>Expected wait condition was not satisfied within the timeout.</td></tr>

<tr><td>StaleElementReferenceException</td><td>The referenced DOM element is no longer attached to the current page DOM.</td></tr>

<tr><td>ElementClickInterceptedException</td><td>Another element prevents the target from being clicked.</td></tr>

<tr><td>InvalidSelectorException</td><td>Locator syntax is invalid.</td></tr>

<tr><td>NoSuchFrameException</td><td>Requested frame could not be found.</td></tr>

<tr><td>NoSuchWindowException</td><td>Requested browser window no longer exists.</td></tr>

<tr><td>WebDriverException</td><td>General WebDriver-related failure.</td></tr>

</table>

<hr>

<h2>52. Common WebDriver Mistakes</h2>

<ul>

<li>Using unstable locators.</li>

<li>Using hard-coded sleeps everywhere.</li>

<li>Not waiting for dynamic elements.</li>

<li>Forgetting to close browser sessions.</li>

<li>Mixing incompatible dependencies.</li>

<li>Creating duplicated page interaction code.</li>

<li>Using JavaScript when a normal WebDriver operation would work.</li>

<li>Ignoring screenshots and logs when diagnosing failures.</li>

<li>Hard-coding environment-specific values.</li>

</ul>

<hr>

<h2>53. Best Practices for WebDriver with Java</h2>

<ol>

<li>Use stable and meaningful locators.</li>

<li>Prefer explicit waits for specific dynamic conditions.</li>

<li>Keep test data separate from test logic.</li>

<li>Use Page Object Model for larger projects.</li>

<li>Use Maven for dependency management.</li>

<li>Use TestNG or JUnit for structured test execution.</li>

<li>Always clean up WebDriver sessions.</li>

<li>Capture useful logs and screenshots for failures.</li>

<li>Keep browser configuration centralized.</li>

<li>Avoid unnecessary <code>Thread.sleep()</code> calls.</li>

<li>Design tests to be independent whenever possible.</li>

<li>Run tests in multiple browsers when cross-browser coverage is required.</li>

</ol>

<hr>

<h2>54. Practical Project: Login Automation</h2>

<p>Consider a web application containing a login page with username, password, and login button.</p>

<pre><code>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();

        }

    }

}</code></pre>

<hr>

<h2>55. Practical Selenium Automation Flow</h2>

<pre><code>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</code></pre>

<hr>

<h2>56. WebDriver Test Framework Structure</h2>

<pre><code>selenium-framework/

├── pom.xml

├── src/

│   ├── main/

│   │   └── java/

│   │       ├── pages/

│   │       ├── utilities/

│   │       └── base/

│   └── test/

│       └── java/

│           └── tests/

└── test-data/

    ├── users.json

    └── testdata.csv</code></pre>

<hr>

<h2>57. WebDriver and Assertions</h2>

<p>Assertions verify whether the actual application behavior matches the expected result.</p>

<p>Example using TestNG:</p>

<pre><code>import static org.testng.Assert.assertEquals;

 

String actualTitle = driver.getTitle();

 

assertEquals(actualTitle, "Expected Title");</code></pre>

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

<hr>

<h2>58. WebDriver and Maven Commands</h2>

<pre><code>mvn -version

mvn clean

mvn compile

mvn test

mvn clean test

mvn package

mvn dependency:tree</code></pre>

<p>These commands are useful for building and executing Selenium Java Maven projects.</p>

<hr>

<h2>59. WebDriver and Debugging</h2>

<p>When a Selenium test fails, check the following:</p>

<ul>

<li>Is the browser installed and accessible?</li>

<li>Is the Selenium dependency available?</li>

<li>Is the locator correct?</li>

<li>Is the page fully loaded?</li>

<li>Is the element inside an iframe?</li>

<li>Is the element located in another window or tab?</li>

<li>Is the element dynamically rendered?</li>

<li>Is an explicit wait required?</li>

<li>Did the DOM change after the element was located?</li>

<li>Are browser and Selenium components compatible?</li>

</ul>

<hr>

<h2>60. WebDriver Interview Questions</h2>

<h3>Q1. What is Selenium WebDriver?</h3>

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

<h3>Q2. What is WebDriver in Java?</h3>

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

<h3>Q3. What is the difference between WebDriver and ChromeDriver?</h3>

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

<h3>Q4. What is WebElement?</h3>

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

<h3>Q5. What is the use of By?</h3>

<p><code>By</code> provides locator strategies such as ID, name, CSS selector, XPath, and class name.</p>

<h3>Q6. What is the difference between close() and quit()?</h3>

<p><code>close()</code> closes the current browser window, while <code>quit()</code> ends the WebDriver session and closes its associated windows.</p>

<h3>Q7. What is an explicit wait?</h3>

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

<h3>Q8. Why is Page Object Model used?</h3>

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

<h3>Q9. How can Selenium handle multiple windows?</h3>

<p>Selenium provides window handles through <code>getWindowHandle()</code> and <code>getWindowHandles()</code>, followed by <code>switchTo().window()</code>.</p>

<h3>Q10. How can Selenium handle frames?</h3>

<p>The driver can switch into a frame using <code>switchTo().frame()</code> and return to the main document using <code>switchTo().defaultContent()</code>.</p>

<hr>

<h2>61. Quick Revision Table</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Task</th><th>Java Selenium Code</th></tr>

<tr><td>Create Chrome session</td><td><code>new ChromeDriver()</code></td></tr>

<tr><td>Open URL</td><td><code>driver.get("URL")</code></td></tr>

<tr><td>Find element</td><td><code>driver.findElement(By.id("x"))</code></td></tr>

<tr><td>Find multiple elements</td><td><code>driver.findElements(By.tagName("a"))</code></td></tr>

<tr><td>Enter text</td><td><code>element.sendKeys("text")</code></td></tr>

<tr><td>Click</td><td><code>element.click()</code></td></tr>

<tr><td>Read text</td><td><code>element.getText()</code></td></tr>

<tr><td>Get title</td><td><code>driver.getTitle()</code></td></tr>

<tr><td>Get URL</td><td><code>driver.getCurrentUrl()</code></td></tr>

<tr><td>Go back</td><td><code>driver.navigate().back()</code></td></tr>

<tr><td>Refresh</td><td><code>driver.navigate().refresh()</code></td></tr>

<tr><td>Maximize</td><td><code>driver.manage().window().maximize()</code></td></tr>

<tr><td>Explicit wait</td><td><code>new WebDriverWait(driver, Duration.ofSeconds(10))</code></td></tr>

<tr><td>Switch to alert</td><td><code>driver.switchTo().alert()</code></td></tr>

<tr><td>Switch to frame</td><td><code>driver.switchTo().frame(...)</code></td></tr>

<tr><td>Switch window</td><td><code>driver.switchTo().window(...)</code></td></tr>

<tr><td>Close session</td><td><code>driver.quit()</code></td></tr>

</table>

<hr>

<h2>62. Complete WebDriver with Java Example</h2>

<pre><code>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();

        }

    }

}</code></pre>

<hr>

<h2>63. Real-World Applications of WebDriver with Java</h2>

<ul>

<li>Login and logout testing.</li>

<li>E-commerce checkout testing.</li>

<li>Registration form testing.</li>

<li>Search functionality testing.</li>

<li>Shopping cart validation.</li>

<li>Banking application UI testing.</li>

<li>Enterprise application regression testing.</li>

<li>Cross-browser testing.</li>

<li>Smoke and sanity testing.</li>

<li>Regression test automation.</li>

<li>CI/CD browser test execution.</li>

<li>End-to-end web application testing.</li>

</ul>

<hr>

<h2>64. WebDriver Automation Best-Practice Flow</h2>

<pre><code>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</code></pre>

<hr>

<h2>65. Summary</h2>

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

<p>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.</p>

<hr>

<h2>66. Course Resources</h2>

<p>Learn more about Selenium and WebDriver with Java through the following resources:</p>

<ul>

<li><a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Selenium Training Course</a></li>

<li><a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Selenium Course Demo</a></li>

</ul>

</div>

Previous Next
whatsapp