Selenium 4 Cheat Sheet: 50+ Commands for SDETs (2026)

Date:

Share post:

Updated Feb 2026: Selenium 4.18+, Chrome 122+, WebDriverManager 5.6+

Selenium remains essential for legacy framework maintenance and specific browser requirements despite Playwright’s rise.

๐Ÿš€ WebDriver Setup (Auto-Managed)

// Chrome (Recommended)
WebDriver driver = new ChromeDriver();

// Firefox
WebDriver driver = new FirefoxDriver();

// Edge
WebDriver driver = new EdgeDriver();

// Headless Chrome (CI/CD)
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless", "--no-sandbox", "--disable-dev-shm-usage");
WebDriver driver = new ChromeDriver(options);

๐Ÿงญ Browser Navigation

driver.get("https://example.com");                    // Direct URL
driver.navigate().to("https://example.com"); // Navigate object
driver.navigate().back(); // Browser back
driver.navigate().forward(); // Browser forward
driver.navigate().refresh(); // Page refresh

String title = driver.getTitle(); // Page title
String url = driver.getCurrentUrl(); // Current URL
String source = driver.getPageSource(); // HTML source

๐Ÿ–ฅ๏ธ Browser Operations

driver.manage().window().maximize();                  // Maximize
driver.manage().window().minimize(); // Minimize
driver.manage().window().fullscreen(); // Fullscreen

driver.quit(); // Close all windows + end session
driver.close(); // Close current window only

๐ŸŽฏ Element Locators (Priority Order)

PriorityStrategySyntaxSpeed
1IDBy.id("submit-btn")โšก Fastest
2CSSBy.cssSelector("#submit.btn-primary")๐Ÿš€ Fast
3NameBy.name("username")โœ… Good
4XPathBy.xpath("//button[@data-test='submit']")๐ŸŒ Slowest
// Multiple elements
List<WebElement> elements = driver.findElements(By.cssSelector(".item"));

// Absence check
Assert.assertTrue(driver.findElements(By.id("nonexistent")).isEmpty());

โณ Waits (Essential!)

// โŒ NEVER USE Thread.sleep() - Anti-pattern!

// Implicit Wait (Global)
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

// Explicit Wait (Recommended)
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.elementToBeClickable(By.id("submit")));

// Fluent Wait (Advanced)
Wait<WebDriver> fluentWait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofSeconds(2))
.ignoring(NoSuchElementException.class);

๐Ÿ”˜ Web Elements

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

element.sendKeys("testuser"); // Type text
element.click(); // Click
element.clear(); // Clear input

String text = element.getText(); // Visible text
String attr = element.getAttribute("value"); // Attribute value

boolean displayed = element.isDisplayed(); // Visible?
boolean enabled = element.isEnabled(); // Clickable?
boolean selected = element.isSelected(); // Checkbox/radio
WebElement dropdown = driver.findElement(By.id("country"));
Select select = new Select(dropdown);

select.selectByVisibleText("India"); // By text
select.selectByValue("IN"); // By value
select.selectByIndex(1); // By position

// Multi-select
select.deselectByValue("IN");
select.deselectAll();

๐Ÿšจ Alerts & Popups

Alert alert = driver.switchTo().alert();
alert.accept(); // OK
alert.dismiss(); // Cancel
String text = alert.getText(); // Message
alert.sendKeys("input"); // Prompt only

๐ŸชŸ Windows & Frames

// Windows/Tabs
String mainWindow = driver.getWindowHandle();
for(String window : driver.getWindowHandles()) {
driver.switchTo().window(window);
if(!window.equals(mainWindow)) driver.close();
}
driver.switchTo().window(mainWindow);

// Frames/iFrames
driver.switchTo().frame("frameId"); // By ID/Name
driver.switchTo().frame(0); // By index
driver.switchTo().frame(driver.findElement(By.tagName("iframe")));
driver.switchTo().defaultContent(); // Back to main

๐Ÿ“ธ Screenshots (Debug Gold!)

// Full page
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("screenshot.png"));

// Element screenshot
File elementShot = element.getScreenshotAs(OutputType.FILE);

๐ŸŽญ Actions Class (Advanced Interactions)

Actions actions = new Actions(driver);
actions.moveToElement(element).perform(); // Hover
actions.contextClick(element).perform(); // Right-click
actions.doubleClick(element).perform(); // Double-click
actions.dragAndDrop(source, target).perform(); // Drag & drop

โš™๏ธ JavaScript Executor

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollTo(0, 500);"); // Scroll
js.executeScript("arguments[0].click();", element); // Force click
String title = js.executeScript("return document.title;").toString();

โ˜๏ธ Headless Mode (CI/CD)

ChromeOptions options = new ChromeOptions();
options.addArguments(
"--headless=new", // New headless (2023+)
"--window-size=1920,1080",
"--disable-gpu",
"--no-sandbox"
);
WebDriver driver = new ChromeDriver(options);

โœ… TestNG Assertions

Assert.assertEquals(actual, expected, "Message");      // Equality
Assert.assertTrue(condition, "Must be true"); // Condition
Assert.assertFalse(condition, "Must be false"); // Negative
Assert.assertNotNull(element, "Element required");

โš ๏ธ Common Exceptions & Fixes

ExceptionCauseFix
NoSuchElementLocator wrongVerify selector in DevTools
StaleElementDOM refreshRe-locate after page change
TimeoutElement slowExplicit Wait > Implicit
ElementNotInteractableHidden/Disabledjs.click() or scroll into view

๐ŸŽฏ Pro Tips for SDETs

  1. Alwaysย use Explicit Waits over Thread.sleep()
  2. Preferย CSS selectors over XPath (10x faster)
  3. Useย WebDriverManagerย – no manual driver downloads:javaWebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver();
  4. Page Object Modelย – never use raw locators in tests
  5. Screenshot on failureย – TestNGย @AfterMethodย listener

Download Printable PDF: [Link to cheatsheet PDF]


Selenium WebDriver 2026 Cheat Sheet – Exhaustive

1. ๐Ÿณ WebDriver Setup & Management

ActionJava CodeNotes
ChromeDriverWebDriver driver = new ChromeDriver();Auto-managed via Selenium Manager
FirefoxDriverWebDriver driver = new FirefoxDriver();GeckoDriver auto-download
EdgeDriverWebDriver driver = new EdgeDriver();Edge WebDriver
Headless ChromeChromeOptions ops = new ChromeOptions(); ops.addArguments("--headless=new");CI/CD essential
Window Sizedriver.manage().window().setSize(new Dimension(1920,1080));Responsive testing
Maximizedriver.manage().window().maximize();Default for desktop
Minimizedriver.manage().window().minimize();macOS only
Fullscreendriver.manage().window().fullscreen();Kiosk mode
Quit Sessiondriver.quit();Always use – closes all windows
Close Windowdriver.close();Current window only

2. ๐ŸŒ Browser Navigation & Info

ActionJava CodeReturns
Navigate GETdriver.get("https://example.com");void
Navigate TOdriver.navigate().to("https://example.com");void
Backdriver.navigate().back();void
Forwarddriver.navigate().forward();void
Refreshdriver.navigate().refresh();void
Current URLdriver.getCurrentUrl();String
Page Titledriver.getTitle();String
Page Sourcedriver.getPageSource();String (HTML)

3. ๐ŸŽฏ Locators (Priority: ID > CSS > XPath)

PriorityStrategySyntaxExample
1IDBy.id("submit")driver.findElement(By.id("login-btn"))
2CSS SelectorBy.cssSelector("#submit.btn")By.cssSelector("input[type='email']")
3NameBy.name("username")By.name("password")
4Class NameBy.className("btn-primary")Multiple classes: .class1.class2
5Tag NameBy.tagName("input")Rarely used alone
6Link TextBy.linkText("Click Here")Exact match
7Partial LinkBy.partialLinkText("Click")Contains text
8XPathBy.xpath("//button[@data-test='submit']")Last resort

Find Multiple Elements:

List<WebElement> elements = driver.findElements(By.cssSelector(".item"));
// Check absence: elements.isEmpty()

4. โณ Waits (Critical!)

Wait TypeCodeWhen to Use
Implicitdriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));Global timeout
Explicitnew WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(locator));RECOMMENDED
Fluentnew FluentWait(driver).withTimeout(Duration.ofSeconds(30)).ignoring(NoSuchElementException.class);Custom polling
Page Loaddriver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));Slow pages
Scriptdriver.manage().timeouts().setScriptTimeout(Duration.ofSeconds(10));JS execution

Common ExpectedConditions:

visibilityOfElementLocated(locator)
elementToBeClickable(locator)
presenceOfElementLocated(locator)
textToBePresentInElement(element, "text")
numberOfWindowsToBe(2)

5. ๐Ÿ”˜ WebElement Operations

ActionCodeReturns
Send Keyselement.sendKeys("test@example.com");void
Clickelement.click();void
Clearelement.clear();void
Get Textelement.getText();String
Get Attributeelement.getAttribute("value");String
Is Displayedelement.isDisplayed();boolean
Is Enabledelement.isEnabled();boolean
Is Selectedelement.isSelected();boolean (checkbox/radio)

6. ๐Ÿ“‹ Dropdown Operations (Select Class)

ActionCodeNotes
InitializeSelect select = new Select(dropdownElement);<select> only
Select by Textselect.selectByVisibleText("India");User-visible text
Select by Valueselect.selectByValue("IN");value attribute
Select by Indexselect.selectByIndex(0);0-based position
Get Selectedselect.getFirstSelectedOption().getText();Single select
Deselectselect.deselectByValue("IN");Multi-select only
Deselect Allselect.deselectAll();Multi-select

7. ๐Ÿšจ Alerts & Popups

ActionCodeNotes
Switch to Alertdriver.switchTo().alert();JS confirm/prompt
Accept (OK)alert.accept();void
Dismiss (Cancel)alert.dismiss();void
Get Textalert.getText();String
Send Keysalert.sendKeys("input");Prompts only

8. ๐ŸชŸ Windows, Tabs & Frames

Windows/Tabs:

ActionCode
Get Currentdriver.getWindowHandle();
Get Alldriver.getWindowHandles();
Switch Windowdriver.switchTo().window(handle);
Close & Switch Backdriver.close(); driver.switchTo().window(mainWindow);

Frames/iFrames:

ActionCode
Frame by Indexdriver.switchTo().frame(0);
Frame by Name/IDdriver.switchTo().frame("frameName");
Frame by Elementdriver.switchTo().frame(element);
Back to Defaultdriver.switchTo().defaultContent();

9. ๐Ÿ“ธ Screenshots

TypeCode
Full Page((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
Elementelement.getScreenshotAs(OutputType.FILE);
Base64((TakesScreenshot)driver).getScreenshotAs(OutputType.BASE64);
// Save to file
File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("screenshot.png"));

10. ๐ŸŽญ Actions Class (Advanced)

ActionCode
Hovernew Actions(driver).moveToElement(element).perform();
Right Clicknew Actions(driver).contextClick(element).perform();
Double Clicknew Actions(driver).doubleClick(element).perform();
Drag & Dropnew Actions(driver).dragAndDrop(source, target).perform();
Click & Holdnew Actions(driver).clickAndHold(element).release().perform();
Scroll to Elementnew Actions(driver).scrollToElement(element).perform();

11. โš™๏ธ JavaScript Executor

ActionCode
Scroll Down(JavascriptExecutor)driver.executeScript("window.scrollBy(0,500);");
Force Click(JavascriptExecutor)driver.executeScript("arguments[0].click();", element);
Get Titledriver.executeScript("return document.title;").toString();
Set Attributedriver.executeScript("arguments[0].value='test';", element);
Check Visibilitydriver.executeScript("return arguments[0].checkVisibility();", element);

12. ๐Ÿช Cookies Management

ActionCode
Get Alldriver.manage().getCookies();
Add Cookiedriver.manage().addCookie(new Cookie("key", "value"));
Delete Nameddriver.manage().deleteCookieNamed("session");
Delete Alldriver.manage().deleteAllCookies();

13. โœ… TestNG Assertions

AssertionCodeValidates
EqualsAssert.assertEquals(actual, expected);Equality
TrueAssert.assertTrue(condition);Boolean true
FalseAssert.assertFalse(condition);Boolean false
Not NullAssert.assertNotNull(element);Object exists
Not EmptyAssert.assertFalse(elements.isEmpty());Collection

14. โฑ๏ธ Timeouts

TimeoutCode
Page Loaddriver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));
Scriptdriver.manage().timeouts().setScriptTimeout(Duration.ofSeconds(10));
Implicitdriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

15. ๐Ÿ“ File Upload

ActionCode
Simple Uploaddriver.findElement(By.id("file")).sendKeys("/path/to/file.png");

16. ๐Ÿšซ Common Exceptions

ExceptionCauseFix
NoSuchElementExceptionWrong locatorVerify in DevTools
StaleElementReferenceExceptionPage refreshedRe-find element
TimeoutExceptionToo slowExplicit Wait
ElementNotInteractableExceptionHidden/disabledScroll + JS click
ElementClickInterceptedExceptionOverlay blockingActions or JS click

๐ŸŽฏ SDET Pro Tips (2026)

  1. WebDriverManagerย – Never download drivers manually:javaWebDriverManager.chromedriver().setup();
  2. Locator Priority: ID > CSS > XPath (10x speed difference)
  3. Alwaysย Explicit Waits,ย Neverย Thread.sleep()
  4. Screenshot on Failureย – TestNG listener:java@AfterMethod public void tearDown(ITestResult result) { if(ITestResult.FAILURE == result.getStatus()) { // Take screenshot } }

๐Ÿ”ฅ Level Up Your SDET Skills ๐Ÿ”ฅ

Monthly Drop : Real-world automation โ€ข Advanced interview strategies โ€ข Members-only resources

Captain Jarhead
Captain Jarhead
Captain Jarhead is a fearless Java expert with a mission to conquer bugs, optimize code, and brew the perfect Java app. Armed with a JVM and an endless supply of caffeine, Captain Jarhead navigates the wild seas of code, taming exceptions and turning null pointers into smooth sailing. A true master of beans, loops, and classes, Captain Jarhead ensures no bug escapes his radar!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Advertisement

Related articles

TG vs ASG: AWS Scaling Secrets for SDETs

Why Scaling Breaks Your Tests (And How TG/ASG Fix It) Your Selenium Grid just went down during peak load....

Auto-Wait Magic: Playwright’s Flake-Proof Secret

If your Selenium tests pass locally but fail in CI, this article is for you. If youโ€™ve added Thread.sleep()...

Top 10 Python Testing Frameworks for QA & SDETs

Python dominates testing in 2026 with 78% AI adoption in QA teams and PyTest used by 12,516+ companies including Amazon, Apple, and IBM. Selenium...

TestNG 7.12.0: Ultimate Guide for Testers & SDETs

Introduction: Why TestNG Still Matters for Testers TestNG remains one of the most widely used Java testing frameworks for...