Selenium commands help automate browser actions and test web applications efficiently. They form the foundation of any Selenium script, enabling developers and testers to simulate user interactions and validate functionality.
Overview
What are Selenium Commands?
Selenium commands are methods provided by the Selenium WebDriver API to perform tasks like clicking elements, entering text, navigating pages, and verifying conditions in a web browser.
Top Selenium Commands
Mastering these essential commands can greatly enhance the speed and reliability of your test automation.
- driver.get(url) – Opens the specified URL in the browser.
- driver.findElement(By.locator) – Locates a single web element using a specified strategy (like ID, name, or CSS selector).
- element.click() – Simulates a mouse click on a web element.
- element.sendKeys(“text”) – Types the given input into a text field or textarea.
- driver.navigate().back() – Navigates to the previous page in the browser history.
- driver.quit() – Closes all browser windows and ends the WebDriver session.
This article explains what Selenium commands are and highlights the most commonly used ones that are essential for building effective automated test scripts.
What are Selenium Commands?
Selenium commands refer to the predefined methods (such as getTitle(), getCurrentUrl(), click(), and more) provided by Selenium WebDriver that enables interaction with web elements and control browser behavior during test automation.
These commands help automate various browser tasks, such as navigating between tabs and windows, clicking on buttons or other elements, getting the current page title or URL, entering text in the text box, and many more. These methods are accessed by using a driver object and calling driver.methodName().
Also Read: Architecture of Selenium WebDriver
Examples:
driver.get(“https://www.browserstack.com”); driver.switchTo().frame(1);
Browser Commands in Selenium
Browser commands provide control over the browser’s actions, which include opening a browser, performing actions on a web browse,r and closing it.
These include launching a web page, fetching page title, page URL, source URL, closing the web page/ browser, etc.
1. Get command: This method loads a new web page in the existing browser window, accepting a String as a parameter and returning void.
Syntax:
get(String URL)
2. Get title command: This method fetches the title of the current web page, takes no parameters, and returns a String.
Syntax:
getTitle()
Example:
String title=driver.getTitle();
3. Get current URL command: This command fetches the URL of the current web page, takes no parameters, and returns a String.
Syntax:
getCurrentUrl()
Example:
String URL=driver. getCurrentUrl();
4. Get page source command: This command fetches the source code of the current web page on the current web browser. It takes no parameter and returns a String.
Syntax:
getPageSource()
Example:
String pageSource=driver. getPageSource();
5. Close command: This method closes the current web page that the driver is pointing to on the current browser window. If the current web page is the only browser window, it also terminates the browser window.
Syntax:
close()
Example:
driver.close();
6. Quit command: This method terminates all the windows operated by the WebDriver. It accepts no parameter and returns void.
Syntax:
quit()
Example:
driver. quit();
Navigational Commands in Selenium
Navigational commands help perform operations that involve navigating through web pages. They also efficiently manage a browser’s history and perform actions like going back, forward, and refreshing the current page.
1. Navigate To command: This method loads a new page in the existing browser window, takes a String as a parameter, and returns void.
Syntax:
navigate().to(String URL)
Example:
driver.navigate().to(“https://www.browserstack.com”);
2. Forward command: This method enables the web browser to click on the forward button in the existing browser window. It accepts no parameter and returns void.
Syntax:
navigate().forward()
Example:
driver.navigate().forward();
3. Back command: This method enables the web browser to click on the back button in the existing browser window. It accepts no parameter and returns void.
Syntax:
navigate().back()
Example:
driver.navigate().back();
4. Refresh command: This method refreshes the current web page in the existing web browser window. It accepts no parameter and returns void.
Syntax:
navigate().refresh()
Example:
driver.navigate().refresh();
WebElement Commands in Selenium
A web element is an HTML element that contains a start and end tag and the content in between. Selenium provides a way to interact with all the web elements present on the web page with the help of web element commands.
Actions such as sending keys, clicking on a button, reading text values, checking-unchecking radio buttons, selecting from a drop-down button, etc. can be performed with Selenium’s web element commands.
Some of the Webelement commands are as follows:
1. Click command: This method performs click operation on a web element.
Syntax:
click()
Example:
WebElement ele=driver.findElement(By.id(“locator id”)); ele.click();
2. SendKeys command: This method enters text into the editable field and takes a String as a parameter.
Syntax:
sendKeys(String text)
Example:
WebElement ele=driver.findElement(By.id(“textbox id”)); ele.sendKeys(“Hello”);
3. Clear command: This command is used to clear the text area’s content. It takes no parameter and returns void.
Syntax:
clear()
Example:
WebElement ele=driver.findElement(By.id(“textbox id”)); ele.sendKeys(“Hello”); ele.clear();
4. Get text command: This method is used to retrieve the inner text of the web element, which CSS does not hide. It takes no parameter and returns a String.
Syntax:
getText()
Example:
WebElement ele=driver.findElement(By.id(“textbox id”)); String text= ele. getText();
5. Get Attribute command: This method retrieves the value of a specified attribute of a web element. It takes a String as a parameter and returns a String.
Syntax:
getAttribute(String attribute)
Example:
WebElement ele=driver.findElement(By.id(“textbox id”)); String value = ele. getAttribute(“id”); // Returns the “id” attribute
6. Get Location command: This method retrieves the location of a specific web element on the web page in terms of X and Y coordinates.
Syntax:
getLocation()
Example:
WebElement ele=driver.findElement(By.id(“textbox id”)); Point point = ele. getLocation(); System.out.println("X cordinate : " + point.x + "Y cordinate: " + point.y);
7. Get CSS Value command: This method fetches the CSS property value of the given web element. It takes no parameter and returns a String value.
Syntax:
getCssValue()
Example:
WebElement ele=driver.findElement(By.id(“textbox id”)); String cssValue= ele.getCssValue();
8. Is Enabled command: This command is used to verify if a particular web element is enabled on the web page. It returns a boolean true value if the element is enabled or false if it is not enabled.
Syntax:
isEnabled()
Example:
WebElement ele=driver.findElement(By.id(“textbox id”)); boolean flag = ele. isEnabled();
9. Is Selected command: This command is used to verify if a particular web element, such as radio or checkbo,x is selected or not. It returns a boolean true value if the element is selected or false if it is not selected.
Syntax:
IsSelected()
Example:
WebElement ele=driver.findElement(By.id(“textbox id”)); boolean flag = ele. IsSelected();
10. Is Displayed command: This command is used to verify if a particular web element is visible on the web page. It returns a boolean true value if the element is displayed or false if it is not displayed.
Syntax:
isDisplayed()
Example:
WebElement ele=driver.findElement(By.id(“textbox id”)); boolean flag = ele.isDisplayed();
Radio Button and Check Box Commands
Radio buttons let a user select only one option from a group, while checkboxes allow selecting one or more options. In Selenium, you can click these elements, deselect them when needed, and confirm if an option is selected. These commands make it easy to work with radio buttons and checkboxes in forms and test their behavior.
1. Click Command
This method is used to select a radio button or a checkbox.
Syntax:
click()
Example:
WebElement radioButton = driver.findElement(By.id("radioOption")); radioButton.click();
2. isSelected Command
This method verifies if a radio button or checkbox is selected. It returns a boolean value — true if selected and false if not.
Syntax:
isSelected()
Example:
WebElement radioButton = driver.findElement(By.id("radioOption")); boolean isChecked = radioButton.isSelected();
3. isEnabled Command
This method verifies if a radio button or checkbox is enabled and can be interacted with.
Syntax:
isEnabled()
Example:
WebElement radioButton = driver.findElement(By.id("radioOption")); boolean isEnabled = radioButton.isEnabled();
Dropdown and Button Commands
Dropdowns let users select an option from a list. They are used when a form has fixed choices, such as a country, state, or category. Buttons perform an action when clicked and can be used to submit a form, add an item to a cart, or move to the next page.
Selenium provides methods for selecting options from a dropdown menu and clicking on buttons. These commands help you mimic user behavior and confirm that forms, searches, and other interactive elements work as expected.
1. Click Command (Button)
This method is used to click a button element. It triggers the action associated with the button, like submitting a form or opening a menu.
Syntax:
click()
Example:
WebElement submitButton = driver.findElement(By.id("submitBtn")); submitButton.click();
2. Select Command (Dropdown)
The Select class in Selenium is used to work with <select> elements. It provides methods to choose options by visible text, value, or index.
Syntax:
Select select = new Select(driver.findElement(By.id("dropdownId"))); select.selectByVisibleText("Option Text"); select.selectByValue("optionValue"); select.selectByIndex(2);
Example:
WebElement dropDown = driver.findElement(By.id("country")); Select select = new Select(dropDown); // Select by visible text select.selectByVisibleText("Canada"); // Select by value select.selectByValue("ca"); // Select by index select.selectByIndex(3);
3. Get Selected Option Command (Dropdown)
This method returns the first selected option in the dropdown.
Syntax:
getFirstSelectedOption()
Example:
WebElement dropDown = driver.findElement(By.id("country")); Select select = new Select(dropDown); WebElement selectedOption = select.getFirstSelectedOption(); String optionText = selectedOption.getText();
Window and Tab Handling Commands
Modern web applications often open links or results in new windows or tabs. In Selenium, you can switch between windows and tabs using built-in methods. These methods help manage multiple pages, making it easy to test scenarios like verifying a link in a new tab or extracting information from a pop‑up window.
1. Get Window Handle Command
This method returns the unique identifier of the current window.
Syntax:
getWindowHandle()
Example:
String mainWindow = driver.getWindowHandle();
2. Get Window Handles Command
This method returns the identifiers of all open windows or tabs.
Syntax:
getWindowHandles()
Example:
Set<String> allWindows = driver.getWindowHandles();
3. Switch To Window Command
This method switches the focus of the driver to a specific window or tab.
Syntax:
switchTo().window(windowHandle)
Example:
for (String handle : allWindows) { driver.switchTo().window(handle); }
4. Close Command
This method closes the current window.
Syntax:
close()
Example:
driver.close();
Frame and iFrame Commands
Frames and iFrames embed another HTML page within a page. In Selenium, you can switch to a frame or iFrame before working with its elements. These commands help move in and out of frames, making locating and testing elements inside them easy.
1. Switch to Frame by Index
Switches the focus to a frame or iFrame based on its position.
Syntax:
switchTo().frame(index)
Example:
// Switch to the second frame on the page driver.switchTo().frame(1); // Now you can locate elements within that frame WebElement form = driver.findElement(By.id("signupForm"));
2. Switch to Frame by Name or ID
Switches the focus to a frame or iFrame using its name or ID attribute.
Syntax:
switchTo().frame("frameName");
Example:
// Switch to the frame with the id "paymentFrame" driver.switchTo().frame("paymentFrame"); // Enter card details driver.findElement(By.name("cardNumber")).sendKeys("4111111111111111");
3. Switch to Frame by Web Element
Switches the focus to a frame using its WebElement.
Syntax:
switchTo().frame(WebElement element)
Example:
WebElement frame = driver.findElement(By.id("iframe")); driver.switchTo().frame(frame);
4. Switch Back to Main Page
Switches the focus from a frame or iFrame back to the main page.
Syntax:
switchTo().defaultContent()
Example:
// Switch back to the main page after working in a frame driver.switchTo().defaultContent(); // Now you can locate elements in the main page WebElement menu = driver.findElement(By.id("mainMenu")); menu.click();
Read More: How to handle iFrame in Selenium
Actions Class Commands
The Actions class in Selenium is used for complex user interactions, such as mouse movements, drag and drop, right clicks, and double clicks. These commands help simulate advanced behavior that goes beyond basic clicks and typing.
1. Mouse Hover Command
Moves the mouse pointer over a specific element.
Syntax:
moveToElement(WebElement element)
Example:
WebElement menu = driver.findElement(By.id("menu")); Actions action = new Actions(driver); action.moveToElement(menu).perform();
2. Drag and Drop Command
Drags an element and drops it to a target location.
Syntax:
dragAndDrop(WebElement source, WebElement target)
Example:
WebElement source = driver.findElement(By.id("source")); WebElement target = driver.findElement(By.id("target")); new Actions(driver).dragAndDrop(source, target).perform();
3. Right Click Command
Performs a right click on an element.
Syntax:
contextClick(WebElement element)
Example:
WebElement element = driver.findElement(By.id("element")); new Actions(driver).contextClick(element).perform();
4. Double-Click Command
Performs a double click on an element.
Syntax:
doubleClick(WebElement element)
Example:
WebElement element = driver.findElement(By.id("element")); new Actions(driver).doubleClick(element).perform();
Synchronization and Wait Commands
Selenium wait commands handle delays and ensure elements are available before interaction. These commands help you write stable and reliable test scripts.
1. Implicit Wait Command
Adds a wait time for finding elements. The driver will poll the page until the element is found or the time expires.
Syntax:
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
Example:
// Set implicit wait to 10 seconds driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10)); // Now any element search will wait up to 10 seconds WebElement element = driver.findElement(By.id("elementId"));
2. Explicit Wait Command
Waits for a specific condition, like an element being visible or clickable.
Syntax:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("elementId")));
Example:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); // Wait until the login button is visible WebElement loginButton = wait.until( ExpectedConditions.visibilityOfElementLocated(By.id("loginButton")) ); // Click the button once it's visible loginButton.click();
3. Fluent Wait Command
Waits for an element with polling at regular intervals and can ignore certain exceptions.
Syntax:
Wait<WebDriver> wait = new FluentWait<>(driver) .withTimeout(Duration.ofSeconds(30)) .pollingEvery(Duration.ofSeconds(5)) .ignoring(NoSuchElementException.class);
Example:
WebElement element = wait.until(driver -> driver.findElement(By.id("elementId")));
New Features and Commands in Selenium 4
Selenium 4 introduced new commands and improved features that make test automation more flexible. These include Locators for finding elements based on their position relative to other components. This makes it easier to build test scripts that are both reliable and readable.
1. Relative Locators
Selenium 4 added Relative Locators to locate elements based on their position in relation to other elements. This makes it simple to build robust locators when fixed identifiers aren’t available.
- above() – Finds an element located above a specific element.
Syntax:
WebElement elem = driver.findElement(By.id("elementId")); WebElement aboveElement = driver.findElement(withTagName("div").above(elem));
- below() – Finds an element located below a specific element.
Syntax:
WebElement elem = driver.findElement(By.id("elementId")); WebElement belowElement = driver.findElement(withTagName("div").below(elem));
- toLeftOf() – Finds an element located to the left of a specific element.
Syntax:
WebElement elem = driver.findElement(By.id("elementId")); WebElement leftElement = driver.findElement(withTagName("div").toLeftOf(elem));
- toRightOf() – Finds an element located to the right of a specific element.
Syntax:
WebElement elem = driver.findElement(By.id("elementId")); WebElement rightElement = driver.findElement(withTagName("div").toRightOf(elem));
- near() – Finds an element located close to a specific element.
Syntax:
WebElement elem = driver.findElement(By.id("elementId")); WebElement nearElement = driver.findElement(withTagName("div").near(elem));
2. New Window Command
Selenium 4 introduced a simple method for opening and managing new windows or tabs.
Syntax:
driver.switchTo().newWindow(WindowType.TAB); driver.switchTo().newWindow(WindowType.WINDOW);
Example:
WebDriver newTab = driver.switchTo().newWindow(WindowType.TAB); newTab.get("https://www.browserstack.com");
3. New Get Element Screenshot Command
Selenium 4 allows capturing a screenshot of a specific element, making it easy to validate or document results.
Syntax:
element.getScreenshotAs(OutputType.FILE);
Example:
WebElement logo = driver.findElement(By.id("logo")); File screenshot = logo.getScreenshotAs(OutputType.FILE);
How BrowserStack Supports Selenium Testing
BrowserStack is a real device cloud testing platform that provides thousands of real devices and browsers, advanced debugging tools, and seamless automation support. This allows you to run your Selenium scripts exactly as they would run in the hands of a real user, spot issues early, and release better software.
Here are some key features of BrowserStack Automate:
- Selenium Grid at Scale: Launch and scale Selenium test runs instantly, from a handful of sessions to hundreds, without setting up or managing any infrastructure.
- No Local Setup Required: Instantly access browser and device environments without the need for local installations, drivers, or virtual machines.
- Parallel Testing: Run test cases concurrently across browsers and platforms to reduce execution times and speed up feedback.
- Comprehensive Debugging: View screenshots, video recordings, console messages, and network logs to identify and fix test failures quickly.
- AI Self‑Healing for Locators: Maintain test stability even when elements change, with AI‑driven recovery of broken or updated locators.
- CI/CD Integration: Connect with Jenkins, GitHub Actions, CircleCI, and other CI tools to run automated Selenium tests as part of every build and deployment.
Conclusion
Selenium commands define how scripts locate elements, simulate user interactions, navigate between pages, and validate behavior across different browsers. Understanding these commands gives testers precise control over the flow of automated tests and allows them to cover a wide range of scenarios.
BrowserStack provides the environment where you can test these commands. It hosts an extensive range of devices, supports parallel execution, and captures detailed logs, screenshots, and recordings for every test run.
Useful Resources for Selenium
Methods, Classes, and Commands
- Selenium Commands every Developer or Tester must know
- Selenium WebElement Commands
- Desired Capabilities in Selenium Webdriver
- Assert and Verify Methods in Selenium
- Understanding System setProperty in Selenium
- Select Class in Selenium : How to select a value in dropdown list?
- SendKeys in Selenium WebDriver
- getAttribute() method in Selenium: What, Why, and How to use
- How does Selenium isDisplayed() method work?
- findElement vs findElements in Selenium
- Types of Listeners in Selenium (with Code Examples)
- How to set Proxy in Firefox using Selenium WebDriver?
Configuration
- How to set up Selenium on Visual Studio
- How to configure Selenium in Eclipse
- Maven Dependency Management with Selenium
- How to Build and Execute Selenium Projects
XPath
- How to use XPath in Selenium?
- How to find element by XPath in Selenium with Example
- Top Chrome Extensions to find Xpath in Selenium
Locators and Selectors
- Locators in Selenium: A Detailed Guide
- CSS Selector in Selenium: Locate Elements with Examples
- How to Create Object Repository in Selenium
Waits in Selenium
- Wait Commands in Selenium C and C#
- Selenium Wait Commands: Implicit, Explicit, and Fluent Wait
- Understanding Selenium Timeouts
- Understanding ExpectedConditions in Selenium
- Understanding Role of Thread.sleep() in Selenium
Frameworks in Selenium
- Data Driven Framework in Selenium
- Implementing a Keyword Driven Framework for Selenium: A Practical Guide
- Hybrid Framework in Selenium
Miscellaneous
- How to create Selenium test cases
- How to set Proxy in Selenium?
- Difference between Selenium Standalone server and Selenium server
- Exception Handling in Selenium WebDriver
- How to use JavascriptExecutor in Selenium
- How to run your first Selenium test script
- Parallel Testing with Selenium
Best Practices, Tips and Tricks
- Top 5 Challenges Faced During Automation Selenium Testing
- 5 Selenium tricks to make your life easier
- 6 Things to avoid when writing Selenium Test Scripts
- Best Practices for Selenium Test Automation
- Why you should pay attention to flaky Selenium tests
- How to start with Selenium Debugging
- How to make your Selenium test cases run faster
- How to upgrade from Selenium 3 to Selenium 4
- Why you should move your testing to a Selenium Cloud?
Design Patterns in Selenium: Page Object Model and Page Factory
- Design Patterns in Selenium
- Page Object Model and Page Factory in Selenium
- Page Object Model and Page Factory in Selenium C#
- Page Object Model in Selenium and JavaScript
- Page Object Model and Page Factory in Selenium Python
Action Class
- How to handle Action class in Selenium
- How to perform Mouse Hover Action in Selenium
- Understanding Click Command in Selenium
- How to perform Double Click in Selenium?
- How to Drag and Drop in Selenium?
- How to Scroll Down or Up using Selenium Webdriver
- How To verify Tooltip Using Selenium
TestNG and Selenium
- Database Testing using Selenium and TestNG
- How to use DataProvider in Selenium and TestNG?
- All about TestNG Listeners in Selenium
- How to run parallel test cases in TestNG
- How to use TestNG Reporter Log in Selenium: Tutorial
- Prioritizing tests in TestNG with Selenium
JUnit and Selenium
- Understanding JUnit assertions for Selenium Testing with Examples
- How to run JUnit Parameterized Test in Selenium
- How to write JUnit test cases
- JUnit Testing Tutorial: JUnit in Java
- How to create JUnit Test Suite? (with Examples)
Use Cases
- Handling Login Popups in Selenium WebDriver and Java
- How to Launch Browser in Selenium
- How to handle Alerts and Popups in Selenium?
- How to get Selenium to wait for a page to load
- How to Find Element by Text in Selenium: Tutorial
- How to Read/Write Excel Data using Apache POI Selenium
- How to handle Captcha in Selenium
- How to handle multiple windows in Selenium?
- How to handle Multiple Tabs in Selenium
- How to find broken links in Selenium
- How to handle Cookies in Selenium WebDriver
- How to handle iFrame in Selenium
- How to handle Web Tables in Selenium
- How To Validate Text in PDF Files Using Selenium Automation
- Get Current URL in Selenium using Python: Tutorial
Types of Testing with Selenium
- Different Testing Levels supported by Selenium
- How to perform UI Testing with Selenium
- Regression Testing with Selenium: Tutorial
- UI Automation using Python and Selenium: Tutorial
- How to Run Visual Tests with Selenium: Tutorial
- How to perform ETL Automation using Selenium
- Cross Browser Testing in Selenium : Tutorial