Difference between Selenium 3 and Selenium 4

Key Differences Between Selenium 3 and Selenium 4

Feature Selenium 3 🟡 Selenium 4 🟢
WebDriver Protocol Used JSON Wire Protocol (translated commands) Uses W3C WebDriver (faster, no translations)
Relative Locators ❌ Not Available above(), below(), toLeftOf(), toRightOf()
Window & Tab Handling Used driver.switchTo().window() driver.switchTo().newWindow(WindowType.TAB)
Element Screenshot Only full-page screenshots ✅ Capture specific elements
Improved Waits Basic explicit/implicit waits Better network interception & request waits
CDP (Chrome DevTools Protocol) ❌ Not Available ✅ Can intercept network requests, console logs, performance metrics
Headless Mode Used old implementations ✅ Faster, more optimized headless execution
Deprecated Features Still had Actions Class legacy APIs ✅ Removed old APIs, new Improved Actions API

 Key Selenium 4 Features with Code Examples

📌 1. W3C WebDriver (More Stable & Faster)

Selenium 3 used JSON Wire Protocol, which required translating Selenium commands to JSON before sending them to browsers. Selenium 4 follows W3C standards, making execution more stable & faster.

Benefit: Less overhead, better browser compatibility.


📌 2. Relative Locators (Easier Element Identification)

New relative locators allow you to find elements based on visual position.

import static org.openqa.selenium.support.locators.RelativeLocator.with;

WebElement loginButton = driver.findElement(with(By.tagName("button")).below(By.id("password")));
loginButton.click();

Easier than XPath or CSS selectors for nearby elements.


📌 3. Better Window & Tab Handling

Old Way (Selenium 3):

String originalWindow = driver.getWindowHandle();
driver.switchTo().newWindow(WindowType.WINDOW);
driver.switchTo().window(originalWindow);

New Way (Selenium 4 - Simplified)

driver.switchTo().newWindow(WindowType.TAB);  // Opens a new tab

Easier & more reliable handling of multiple tabs.


📌 4. Element-Specific Screenshot

Now you can take screenshots of individual elements instead of the full page.

WebElement logo = driver.findElement(By.id("site-logo"));
File src = logo.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("element_screenshot.png"));

Helps in debugging UI issues faster.


📌 5. Chrome DevTools Protocol (CDP)—Intercept Network Requests

DevTools devTools = ((HasDevTools) driver).getDevTools();
devTools.createSession();
devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));

devTools.addListener(Network.requestWillBeSent(), request -> 
    System.out.println("Request URL: " + request.getRequest().getUrl()));

Allows capturing network requests, modifying responses, and debugging performance.


Should You Upgrade to Selenium 4?

YES! Selenium 4 is more stable, faster, and easier to use.
W3C standardization improves compatibility.
Relative Locators, Tab Handling, and CDP make automation simpler.


Comments

Popular Posts