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
Excellent. Content Simplified in its best way. Please post on pending areas in the index.
ReplyDeletevery helpful to practise these Assignments
ReplyDeleteUseful blog, keep sharing with us.
ReplyDeleteHow to Use Selenium with Java
Why Selenium with Java
The information you've provided is useful because it provides a wealth of knowledge that will be highly beneficial to me. Thank you for sharing that. Keep up the good work. Web Design Tampa
ReplyDeleteNowadays, to complete SEO tasks in minimum time, some SEO service providers use automated tools for directory submission and article submission. sendpulse com
ReplyDeleteprovides digital marketing consultation and lead generation services to small businesses in local markets. He can be contacted through Website Marketing news heraldcorp com
ReplyDeleteThis article provided me with a wealth of information about Full stack web development services for small business. The article is both educational and helpful. Thank you for providing this information. Keep up the good work.
ReplyDeleteThe information you've provided is useful because it provides a wealth of knowledge that will be highly beneficial to me. Thank you for sharing that. Keep up the good work. Graphic Design Company Sydney
ReplyDeleteThe information in the post you posted here is useful because it contains some of the best information available. Thanks for sharing it. Keep up the good work Website Design Company
ReplyDeleteYou have provided valuable data for us. It is great and informative for everyone. Keep posting! also look at this web design agency dubai. I am very thankful to you.
ReplyDeletevery good tutorial thanks for sharing DLF share price
ReplyDelete
ReplyDeleteClipping Path Us is a dedicated clipping path service provider managed by some professional and experienced graphic designers. Our buyers have a good knowledge of our photo editing services and recognize it as one of the best crop path service companies in the world. Clipping Path Service Inc is a model image editing platform. Our clients have benefited their business by using our high quality, professional and affordable Photoshop services. We have more than 150 Photoshop experts to provide all types of image editing tasks. We reportedly provide cropping path, color correction, image masking, neck join, photo retouching, background removal and e-commerce image editing services worldwide. We believe that our clients' success means our success. That is why we are committed to providing high quality work. Clipping Path is an excellent choice for a high quality background removal service from Clipping Path Us. As today's preferred clipping path service provider in Southeast Asia, we provide all types of clipping path services at the lowest price, whether it's image background removal or multi-color correction. So you can rely on us when it comes to road cutting service Clipping path service
#clippingpath #clippingpathservice #backgroundremoval #imagemasking #dropshadowservice #reflectionshadowservice #photoretouchingservice #colorcorrectionservice #ecommerceimageediting #carimageediting #neckjointservice #ghostmannequinservice #invisiblemannequinservice #removefromimage #whitebackgroundremove #photocutout #imageediting #photomanipulation
I am very enthusiastic when I read your articles. Please keep sharing more and more wonderful articles.
ReplyDeleteGreat Job Here! I read a lot of blog posts and I never heard of a topic like this. I like this topic you made about structural engineer sydney. Very ingenious.
ReplyDelete