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

  2. Browser Window Commands

  3. Navigation Commands

  4. Element Location Commands

  5. Element Interaction Commands

  6. Dropdown Handling Commands

  7. Advanced Utility Commands


1. Browser Initialization Commands

System.setProperty()

java

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

java

WebDriver driver = new ChromeDriver();

Explanation:

  • Creates a new browser session

  • ChromeDriver() is a concrete class implementing WebDriver interface

  • Other implementations: FirefoxDriver()EdgeDriver(), etc.

  • Starts a fresh browser profile by default


2. Browser Window Commands

Window Maximization

java

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

java

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

java

driver.manage().window().setPosition(new Point(0, 0));

Explanation:

  • Positions browser window on screen (x, y coordinates)

  • Point class from org.openqa.selenium.Point

  • Helpful for multi-monitor setups

  • Rarely used in standard test scenarios


3. Navigation Commands

java

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

java

driver.navigate().back();
driver.navigate().forward();
driver.navigate().refresh();

Explanation:

  • back(): Simulates browser back button

  • forward(): Simulates browser forward button

  • refresh(): Reloads current page

  • Maintains browser history stack

  • Useful for testing multi-page workflows

URL Information

java

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

java

// 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()

java

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

Explanation:

  • Locates first matching element in DOM

  • Throws NoSuchElementException if not found

  • Returns WebElement object for interaction

  • By strategies: id, name, className, tagName, linkText, partialLinkText, cssSelector, xpath

findElements()

java

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()

java

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()

java

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()

java

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

java

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

java

Select dropdown = new Select(driver.findElement(By.id("country")));

Explanation:

  • Wrapper class for <select> elements

  • Provides specialized dropdown methods

  • Works for both single and multi-select

  • Throws UnexpectedTagNameException if used on non-select

Selection Methods

java

dropdown.selectByVisibleText("Canada");
dropdown.selectByValue("ca");
dropdown.selectByIndex(2);

Explanation:

  • selectByVisibleText(): Matches exact option text

  • selectByValue(): Matches option value attribute

  • selectByIndex(): Zero-based option position

  • Prefer text/value over index for stability

Select Class Usage

java

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

java

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 cast

  • Essential for failure analysis

JavaScript Execution

Scroll Towards an Element

java

((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView()", element);

Scroll By Pixels (Vertical or Horizontal)

java

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

  1. Always maximize the browser window before tests

  2. Prefer CSS selectors over XPath for performance

  3. Use explicit waits instead of static sleeps

  4. Implement Page Object Model for maintainability

  5. Validate element states before interaction

  6. Clean up sessions with quit() after tests

  7. Combine findElement with waits for stability

java

// Good practice example
WebElement element = new WebDriverWait(driver, Duration.ofSeconds(10))
    .until(ExpectedConditions.elementToBeClickable(By.id("submit")));
element.click();

#Selenium #WebDriver #TestAutomation

Selenium Locator Commands  << Previous      ||      Next >>  What is Actions Class in Selenium?

Comments

  1. Excellent. Content Simplified in its best way. Please post on pending areas in the index.

    ReplyDelete
  2. very helpful to practise these Assignments

    ReplyDelete
  3. 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

    ReplyDelete
  4. Nowadays, to complete SEO tasks in minimum time, some SEO service providers use automated tools for directory submission and article submission. sendpulse com

    ReplyDelete
  5. provides digital marketing consultation and lead generation services to small businesses in local markets. He can be contacted through Website Marketing news heraldcorp com

    ReplyDelete
  6. This 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.

    ReplyDelete
  7. 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. Graphic Design Company Sydney

    ReplyDelete
  8. The 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

    ReplyDelete
  9. You 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.

    ReplyDelete

  10. Clipping 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

    ReplyDelete
  11. I am very enthusiastic when I read your articles. Please keep sharing more and more wonderful articles.

    ReplyDelete
  12. Great 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

Post a Comment

Popular posts from this blog

Selenium Automation for E-commerce Websites

Top 10 Demo Websites for Selenium Automation Practice

Mastering Selenium Practice: Automating Web Tables with Demo Examples

Top 10 Highest Paid Indian-Origin CEOs in the USA: Leaders Shaping Industries

14 Best Selenium Exercises to Master Automation Testing Skills

Understanding Cryptocurrency: A Beginner's Guide to Bitcoin and Ethereum

Top 8 AI Tools You Should Start Using Today

Best Budget Tech Gadgets You Can Buy in 2025

Top 20 Selenium Interview Questions & Answers