Selenium 4 Cheatsheet: Essential Automation Testing Guide 2025

Date:

Share post:

Selenium 4 brings a host of game-changing features that modernize test automation frameworks worldwide. With India’s booming software testing industry and growing demand for skilled automation engineers, mastering Selenium 4 is your gateway to career success.

This guide targets software testers, QA engineers, and SDETs aged 22-35 striving to master Selenium 4’s power—whether you are stepping up from manual testing or enhancing existing automation suites.

What’s New in Selenium 4?

FeatureDescriptionCode Snippet / Example
W3C WebDriver ProtocolStandardized browser-driver communication for improved stability and cross-browser consistency.java WebDriver driver = new ChromeDriver(); driver.get("https://qabash.com");
Relative LocatorsFind web elements by relative position: above, below, near, left, right — ideal for dynamic UI layouts.java WebElement loginBtn = driver.findElement(with(By.tagName("button")).below(passwordField));
Enhanced Selenium GridDocker and Kubernetes support with TOML config files; scalable, reliable distributed test execution.(Docker commands to launch hub and nodes)
Chrome DevTools Protocol (CDP)Direct browser control for network interception, debugging, and performance insights integrated into WebDriver.java DevTools devTools = driver.getDevTools(); devTools.createSession();
Selenium ManagerAutomatic management of browser driver binaries with zero manual configuration.java WebDriver driver = new ChromeDriver(); // No manual driver setup
New Window & Tab APIsOpen new browser windows or tabs programmatically within tests.java driver.switchTo().newWindow(WindowType.TAB);

Core Selenium 4 Commands & Usage

Below is a comprehensive and up-to-date tabular reference of all essential Selenium WebDriver commands—including those introduced or modified up to July 2025—and a clear marking of deprecated/obsolete commands with examples and preferred replacements.

Master List of Selenium Commands (2025) with Deprecated (❌) and Examples

CategoryCommand / MethodExampleDeprecated?Notes / Replacement / Comments
Browser Controldriver.get(String url)driver.get(“https://qabash.com“)NoLaunches URL
driver.getTitle()String title = driver.getTitle()NoGets the page title
driver.getCurrentUrl()String url = driver.getCurrentUrl()NoGets current URL
driver.getPageSource()String html = driver.getPageSource()NoGets entire page source
driver.close()driver.close()NoCloses current browser window
driver.quit()driver.quit()NoCloses all browser windows, ends session
Navigationdriver.navigate().back()driver.navigate().back()NoBack in browser history
driver.navigate().forward()driver.navigate().forward()NoForward in browser history
driver.navigate().refresh()driver.navigate().refresh()NoRefresh page
driver.navigate().to(String url)driver.navigate().to(“https://qabash.com“)NoAlternate navigation
Element Locationdriver.findElement(By.id(“id”))driver.findElement(By.id(“username”))NoStandard element lookup
driver.findElement(By.name(“name”))driver.findElement(By.name(“email”))No
driver.findElement(By.className(“c”))driver.findElement(By.className(“profile”))No
driver.findElement(By.xpath(“xpath”))driver.findElement(By.xpath(“//button”))No
driver.findElement(By.cssSelector(“selector”))driver.findElement(By.cssSelector(“.menu”))No
driver.findElement(By.linkText(“text”))driver.findElement(By.linkText(“Sign In”))No
driver.findElement(By.partialLinkText(“txt”))driver.findElement(By.partialLinkText(“Sign”))No
Relative Locatorswith(By…).above(elem)with(By.tagName(“button”)).above(passwordField)NoNew in Selenium 4
with(By…).below(elem)with(By.tagName(“input”)).below(userField)No
with(By…).toLeftOf(elem)with(By.tagName(“button”)).toLeftOf(submitButton)No
with(By…).toRightOf(elem)with(By.tagName(“button”)).toRightOf(cancelButton)No
with(By…).near(elem)with(By.tagName(“img”)).near(usernameField)No
Element Interactelement.click()element.click()NoClicks element
element.sendKeys(“text”)element.sendKeys(“password”)NoTypes text
element.clear()element.clear()NoClears field
element.getText()String text = element.getText()NoGets visible text
element.getAttribute(“attr”)String a = element.getAttribute(“href”)NoGets attribute
element.isDisplayed()boolean vis = element.isDisplayed()NoChecks display
element.isEnabled()boolean en = element.isEnabled()NoChecks enabled
element.isSelected()boolean sel = element.isSelected()NoFor checkboxes/radios
element.submit()element.submit()NoSubmits a form
Windows/Tabsdriver.switchTo().window(handle)driver.switchTo().window(windowHandle)NoChanges to window/tab
driver.getWindowHandles()Set<String> handles = driver.getWindowHandles()NoGets all open handles
driver.switchTo().newWindow(WindowType.TAB)driver.switchTo().newWindow(WindowType.TAB)NoOpens new tab/window (S4+)
Frames/Alertsdriver.switchTo().frame(int/name/element)driver.switchTo().frame(0)NoSwitches to frame
driver.switchTo().defaultContent()driver.switchTo().defaultContent()NoReturns to main DOM
driver.switchTo().alert()driver.switchTo().alert().accept()NoHandles JS alerts
Waitsdriver.manage().timeouts().implicitlyWait(Duration)driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10))NoUse Duration, NOT TimeUnit as of Selenium 4
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));wait.until(ExpectedConditions.visibilityOf(element));NoExplicit wait
driver.manage().timeouts().implicitlyWait(long, TimeUnit)driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS)❌ YesDeprecated. Use Duration only ()
Advanced / APIJavascriptExecutor, executeScript((JavascriptExecutor)driver).executeScript(“window.scrollBy(0,100)”)NoRuns JS on page
Actions objectnew Actions(driver).contextClick(elem).perform()NoMouse/key complex interactions
DevTools/CDPdriver.getDevTools()DevTools devTools = driver.getDevTools();NoDirect Chrome DevTools (S4+)
Options APIDesiredCapabilities cap = …DesiredCapabilities capabilities = new DesiredCapabilities();❌ YesDeprecated. Use browser-specific Options (ChromeOptions, etc)
options.merge(capabilities)ChromeOptions options = new ChromeOptions(); options.merge(caps);NoIn S4, merged options must be assigned, doesn’t mutate object
Grid/RemoteRemoteWebDrivernew RemoteWebDriver(new URL(hubUrl), options)NoFor Selenium Grid
MiscellaneousFindsBy (interface)❌ YesInternal, replaced with FindElement/FindElements
setLegacyoptions.setLegacy(true);❌ YesRemoved—use GeckoDriver
executable_path (Python)driver = webdriver.Chrome(executable_path=”chromedriver”)❌ YesDeprecated, use driver.Service object
AddAdditionalCapability (C#)options.AddAdditionalCapability(“cloud:options”, opts, true)❌ YesUse AddAdditionalOption
BrowserType.FIREFOXcapabilities.setCapability(“browserName”, BrowserType.FIREFOX)❌ YesUse Browser.FIREFOX

Code Examples of Deprecated & Modern Usage

// DEPRECATED: TimeUnit-based Implicit Wait (Do NOT use, will warn)
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// REPLACEMENT: Use Duration
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
// DEPRECATED: DesiredCapabilities (Do NOT use unless legacy)
DesiredCapabilities caps = new DesiredCapabilities();

// REPLACEMENT: Use browser-specific Options
ChromeOptions options = new ChromeOptions();
// ...set options...
WebDriver driver = new ChromeDriver(options);
# DEPRECATED: direct path (Selenium Python)
driver = webdriver.Chrome(executable_path="chromedriver")

# REPLACEMENT:
from selenium.webdriver.chrome.service import Service
service = Service("chromedriver")
driver = webdriver.Chrome(service=service)

Expert Insight: Always check official docs for your Selenium version, as deprecated APIs may be removed entirely in future releases. Migrate away from DesiredCapabilitiesFindsBy, and TimeUnit-based waits ASAP for stable, maintainable scripts.

  • Use Duration, browser-specific Options, and always favor new Relative Locators, DevTools, and Window APIs.
  • Selenium Manager (new) automates driver downloads—avoid manual path settings.
  • All new and deprecated details are up-to-date as of July 2025.

Pro Tips for Selenium 4 Automation

  • Prefer relative locators over brittle absolute XPaths to make your test resilient to UI changes.
  • Use the Chrome DevTools Protocol integration in Selenium 4 for capturing network requests and performance metrics to add deeper validations.
  • Leverage Selenium Manager to eliminate driver binary management and avoid environment-specific issues.
  • Implement explicit waits with WebDriverWait and avoid Thread.sleep() to create stable and performant tests.
  • Structure test code using Page Object Model (POM) to improve readability and maintainability.

Why Selenium 4 is Crucial for AI Testing Today?

Selenium 4 makes automation testing more powerful and maintainable with features like the W3C WebDriver protocol, relative locators, enhanced Selenium Grid, and Chrome DevTools Protocol integration. Combined with AI testing frameworks, it reduces test maintenance by up to 60%, helping testers adapt swiftly to UI changes and complex workflows.

ToolCategoryBenefitsRecommendation
TestimSelf-Healing Web TestsAI auto-fixes flaky locators, reduces maintenance⭐ Recommended by QABash
ApplitoolsVisual AI TestingCross-browser visual regression with AI⭐ Recommended by QABash
MablLow-Code AI AutomationNatural language test creation & performance monitoring
AccelQCodeless AI TestingML-driven test automation for faster cycles

In our experience with QABash community, integrating these AI tools with Selenium 4 cuts test flakiness and boosts reliability significantly.

Step-by-Step Implementation Guide: Selenium 4 + AI Integration

// Initialize Selenium 4 driver and CDP session
ChromeDriver driver = new ChromeDriver();
DevTools devTools = driver.getDevTools();
devTools.createSession();
devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));

// Example: Use relative locator for more stable element finding
WebElement passwordField = driver.findElement(By.id("password"));
WebElement loginButton = driver.findElement(with(By.tagName("button")).below(passwordField));

// Visual validation with Applitools
Eyes eyes = new Eyes();
eyes.setApiKey(System.getenv("APPLITOOLS_API_KEY"));
eyes.open(driver, "QABash App", "Login Page Test");
eyes.checkWindow("Login Page");
eyes.close();
  1. Setup Selenium 4 and AI tool SDKs with your project dependencies.
  2. Write tests using relative locators and integrate AI visual or self-healing capabilities.
  3. Leverage CDP for performance and network monitoring within your tests.
  4. Run tests on cloud Selenium Grid 4 with Docker for scalable parallel testing.
  • WebDriver BiDi Protocol: Bi-directional real-time browser control enabling sophisticated telemetry and debugging.
  • Natural Language Test Generation: Convert plain English test cases into executable automation scripts with AI.
  • Predictive Flakiness Detection: ML models pre-identify likely failing tests to optimize test runs.
  • Shift-Left AI: Integrate AI-powered testing within CI/CD pipelines for continuous quality and faster feedback.

Frequently Asked Questions (FAQ)

Q1: What’s new in Selenium 4?
A: Selenium 4 introduces several major enhancements, including full support for the W3C WebDriver protocol for better cross-browser compatibility, new Relative Locators to find elements by their position relative to others, integration with Chrome DevTools Protocol for advanced debugging and performance monitoring, an improved Selenium Grid 4 with Docker support, and Selenium Manager which automatically downloads and configures browser drivers.

Q2: How do I use the Relative Locators feature?
A: Relative Locators allow you to find web elements based on their spatial position relative to other elements. For instance, you can locate a button that is “below” or “to the right of” another element, making your tests more stable against UI layout changes. Common methods include above(), below(), near(), toLeftOf(), and toRightOf().

Q3: How do I replace deprecated implicit waits in Selenium?
A: Instead of the older implicit wait that used TimeUnit (e.g., implicitlyWait(10, TimeUnit.SECONDS)), Selenium 4 requires you use the new Duration-based wait API like this: driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10)). This provides a modern and type-safe way to specify timeouts.

Q4: How can I open a new browser tab in Selenium 4?
A: Selenium 4 adds a new way to open new tabs or windows using: driver.switchTo().newWindow(WindowType.TAB) for a new tab, or WindowType.WINDOW for a new window. This command opens the new context and switches focus to it automatically.

Q5: What is Selenium Manager?
A: Selenium Manager is a new feature that automatically manages your browser driver binaries in the background. This means you no longer need to manually download or configure paths for ChromeDriver, GeckoDriver, etc. Selenium Manager makes setup seamless and less error-prone.

QABash Media
QABash Media
Scientist Testbot, endlessly experimenting with testing frameworks, automation tools, and wild test cases in search of the most elusive bugs. Whether it's poking at flaky pipelines, dissecting Selenium scripts, or running clever Lambda-powered tests — QAbash.ai is always in the lab, always learning. ⚙️ Built for testers. Tuned for automation. Obsessed with quality.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Advertisement

Related articles

PRD-Based Ticketing: Transforming the Testing Workflow using BDD

Introduction In software development, clarity in requirements is crucial. When requirements are unclear, testers struggle with ambiguities, leading to...

AI in Testing: Complete Guide for 2025

Introduction The software testing landscape is experiencing a seismic shift. By 2025, 72.3% of testing teams are actively exploring AI-driven...

Top 10 Logic Mistakes SDETs Make & How to Fix Them?

Why Passing Pipelines Still Let Bugs Through? Imagine this: your automation test PR has just been merged. CI pipeline...

How to Build Strong Logic for Automation Testing?

Why Logic is the Secret Sauce in Automation Testing? Imagine this: Your Selenium test runs green, but it misses...