25+ Selenium WebDriver Commands: The Complete Cheat Sheet with Examples
Introduction
This ultimate guide explains every essential Selenium WebDriver command with detailed technical explanations and practical Java examples. Whether you're writing your first test script or optimizing an existing framework, understanding these commands is crucial for effective test automation.
Table of Contents
1. Browser Initialization Commands
System.setProperty()
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
Explanation:
Sets the system property to specify the path to the browser driver executable
Required before creating a WebDriver instance
Must match your browser version (e.g., ChromeDriver for Chrome)
Path can be absolute or relative to project
WebDriver Initialization
WebDriver driver = new ChromeDriver();
Explanation:
Creates a new browser session
ChromeDriver()
is a concrete class implementing WebDriver interfaceOther implementations:
FirefoxDriver()
,EdgeDriver()
, etc.Starts a fresh browser profile by default
2. Browser Window Commands
Window Maximization
driver.manage().window().maximize();
Explanation:
Expands browser window to maximum screen size
Recommended before test execution for consistent element visibility
Prevents responsive layout issues
Alternative to setting specific dimensions
Browser Window Management
driver.manage().window().maximize(); // Maximizes browser window
driver.manage().window().fullscreen(); // Fullscreen mode
driver.manage().window().setSize(new Dimension(1024, 768)); // Set custom size
// Close commands
driver.close(); // Closes current window
driver.quit(); // Closes all windows and ends session
driver.manage().window().maximize(); // Maximizes browser window driver.manage().window().fullscreen(); // Fullscreen mode driver.manage().window().setSize(new Dimension(1024, 768)); // Set custom size // Close commands driver.close(); // Closes current window driver.quit(); // Closes all windows and ends session
Pro Tip: Always use quit()
in teardown to prevent memory leaks.
Window Position
driver.manage().window().setPosition(new Point(0, 0));
Explanation:
Positions browser window on screen (x, y coordinates)
Point
class fromorg.openqa.selenium.Point
Helpful for multi-monitor setups
Rarely used in standard test scenarios
3. Navigation Commands
driver.get("https://www.example.com");
Explanation:
Loads a new web page in current browser session
Waits for full page load before proceeding
Preferred over navigate().to() for initial page loads
Throws exception if page fails to load
Navigation Interface
driver.navigate().back(); driver.navigate().forward(); driver.navigate().refresh();
Explanation:
back()
: Simulates browser back buttonforward()
: Simulates browser forward buttonrefresh()
: Reloads current pageMaintains browser history stack
Useful for testing multi-page workflows
URL Information
String currentUrl = driver.getCurrentUrl(); // Gets current URL String pageTitle = driver.getTitle(); // Gets page title String pageSource = driver.getPageSource(); // Gets HTML source
Best Practice: Use getCurrentUrl()
for page load verification.
4. Element Location Commands
Locating Elements
// Common locators
driver.findElement(By.id("username"));
driver.findElement(By.name("password"));
driver.findElement(By.className("btn"));
driver.findElement(By.tagName("input"));
driver.findElement(By.linkText("Login"));
driver.findElement(By.partialLinkText("Log"));
driver.findElement(By.cssSelector("#login"));
driver.findElement(By.xpath("//button[@type='submit']"));
// Common locators driver.findElement(By.id("username")); driver.findElement(By.name("password")); driver.findElement(By.className("btn")); driver.findElement(By.tagName("input")); driver.findElement(By.linkText("Login")); driver.findElement(By.partialLinkText("Log")); driver.findElement(By.cssSelector("#login")); driver.findElement(By.xpath("//button[@type='submit']"));
findElement()
WebElement element = driver.findElement(By.id("username"));
Explanation:
Locates first matching element in DOM
Throws
NoSuchElementException
if not foundReturns
WebElement
object for interactionBy
strategies: id, name, className, tagName, linkText, partialLinkText, cssSelector, xpath
findElements()
List<WebElement> buttons = driver.findElements(By.tagName("button"));
Explanation:
Returns collection of all matching elements
Returns empty list if none found (no exception)
Useful for counting elements or bulk operations
Requires iteration for individual element access
5. Element Interaction Commands
click()
element.click();
Explanation:
Simulates mouse click on element
Works on buttons, links, checkboxes, etc.
Scrolls element into view automatically (in most browsers)
May fail if element is obscured or disabled
sendKeys()
element.sendKeys("test@example.com");
Explanation:
Types text into input fields
Simulates real keyboard input
Can chain multiple sendKeys() calls
For special keys:
sendKeys(Keys.TAB)
getText()
String labelText = element.getText();
Explanation:
Returns visible text content of element
Excludes hidden text and HTML tags
Returns empty string if no text content
Common for validation assertions
Element Actions
WebElement element = driver.findElement(By.id("username")); element.click(); // Clicks element element.sendKeys("text"); // Enters text element.clear(); // Clears input field String text = element.getText(); // Gets visible text // Element state checks boolean isDisplayed = element.isDisplayed(); boolean isEnabled = element.isEnabled(); boolean isSelected = element.isSelected();
Critical Note: Always verify element visibility before interaction.
6. Dropdown Handling Commands
Select Class
Select dropdown = new Select(driver.findElement(By.id("country")));
Explanation:
Wrapper class for
<select>
elementsProvides specialized dropdown methods
Works for both single and multi-select
Throws
UnexpectedTagNameException
if used on non-select
Selection Methods
dropdown.selectByVisibleText("Canada"); dropdown.selectByValue("ca"); dropdown.selectByIndex(2);
Explanation:
selectByVisibleText()
: Matches exact option textselectByValue()
: Matches option value attributeselectByIndex()
: Zero-based option positionPrefer text/value over index for stability
Select Class Usage
Select dropdown = new Select(driver.findElement(By.id("country"))); // Selection methods dropdown.selectByIndex(1); dropdown.selectByValue("usa"); dropdown.selectByVisibleText("United States"); // Deselection methods dropdown.deselectAll(); dropdown.deselectByIndex(1); // Dropdown information List<WebElement> options = dropdown.getOptions(); WebElement firstSelected = dropdown.getFirstSelectedOption(); boolean isMultiple = dropdown.isMultiple();
Common Pitfall: Don't use selectByIndex()
for dynamic dropdowns.
7. Advanced Utility Commands
Taking Screenshots
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("screenshot.png"));
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(screenshot, new File("screenshot.png"));
Explanation:
Captures current viewport as image file
OutputType can be FILE, BYTES, or BASE64
Requires
TakesScreenshot
interface castEssential for failure analysis
JavaScript Execution
Scroll Towards an Element
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView()", element);
Scroll By Pixels (Vertical or Horizontal)
JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript("window.scrollBy(0,500)"); // Scroll js.executeScript("arguments[0].click();", element); // Click
Explanation:
Executes arbitrary JavaScript
Bypasses some WebDriver limitations
Can return values from scripts
Use sparingly - breaks WebDriver abstraction
Best Practices Summary
Always maximize the browser window before tests
Prefer CSS selectors over XPath for performance
Use explicit waits instead of static sleeps
Implement Page Object Model for maintainability
Validate element states before interaction
Clean up sessions with quit() after tests
Combine findElement with waits for stability
// Good practice example WebElement element = new WebDriverWait(driver, Duration.ofSeconds(10)) .until(ExpectedConditions.elementToBeClickable(By.id("submit"))); element.click();
#Selenium #WebDriver #TestAutomation