Kenneth Etuk @K.Etuk / 7:00 PM EDT. October 04, 2022.
The best Selenium WebDriver Java commands cheat sheet is exactly as it sounds like -- a cheat sheet for all things Selenium WebDriver. Keep reading to discover where I got the command names from, what are the most common commands, and then be sure to see my tutorial on how to get started with Selenium WebDriver (which includes using a headless browser, which is great when testing if your site works offline).
What is WebDriver?
WebDriver is an API used to interact with a browser from an application running on another computer. Selenium is the name of an open-source tool that comes in various languages. This allows developers to write tests for websites and automate them through their programming language of choice.
There are hundreds of WebDriver commands and plugins available for testing Java applications. In this post, I'll show you some of my favourite ways to speed up the Selenium WebDriver testing process simply by using the power of the terminal and your IDE!
This is a handy document to help those who are beginners to test automation to quickly execute web automation using selenium WebDriver with Java programming language. It contains quick guides and references to help you quickly remember Selenium commands and their associated functions.
get() - Used to open a specific URL
If the object of the WebDriver Interface is created and called “driver”
Syntax: driver.get( );
getPageSource( ); - Used to get source code of current page. The page source can be stored into a variable.
getTitle(); - Used to get title of current page. The title can be stored in a variable
getCurrentUrl(); - Used to get URL of current page. URL can be stored into a variable.
Close and Quit commands
close(); - Used to close current tab
quit(); - Used to quit the browser window
IsEnabled, IsSelected, IsDisplayed, sendKeys, click commands
To use these methods, you need to first find the element you intend to interact with (using any of the available ways and store it into a WebElement variable).
Example: WebElement radioButton = driver.findElement(By.id(“id of radio button “));
Boolean status = radioButton.isEnabled();
isEnabled(); - Used to check if an element such as radio button is enabled or not. The result is stored into a Boolean variable.
isSelected(); - Used to check if an element such as checkbox is selected or not. The result is stored into a Boolean variable.
isDisplayed() - Used to check if an element such as input field is displayed or not. The result is stored into a Boolean variable.
sendKeys(); - Used to send text into an input field. It can also be used to press the computer keyboard keys. The Keys class library must be imported into code.
Example: WebElement firstNameField = driver.findElement(By.id(“id of first name field “));
click(); - Used to click on a button or link.
Example: WebElement radioButton = driver.findElement(By.id(“id of radio button “));
Element locator commands
findElement(By.Type of locator) - Used to locate elements on the webpage. This method can be used to locate elements using several ways such as: id, className, name, xpath, linkText, partialLinkText, CssSelector, etc. The By class library must be imported into the code.
Syntax: driver.findElement(By.id(“element id”));
navigate().to(“URL”); - Used to navigate to a new webpage in current browser tab.
Example: Syntax: driver.navigate().to(https://www.facebook.com);
navigate().back(). - Used to navigate to a previous webpage in current browser tab.
navigate().forward(). - Used to navigate to a webpage previously visited and one that was just returned from in current browser tab.
navigate().refresh(). - Used to refresh or reload current webpage in current browser tab.
Thread.sleep, ImplicitWait, ExplicitWait Commands
Thread.sleep(sleep time) - Used in Java to pause the code by the number of time provided in milliseconds. Interrupted exception should be added to code and time library should be imported into code.
implicitWait(time, time unit) - Used by selenium to pause the code and wait for all elements of a webpage to load. Time library should be imported into code.
Syntax: driver.manage().timeouts().implicitWait(timeOut, TimeUnit.SECONDS);
Example: driver.manage().timeouts().implicitWait(20, TimeUnit.SECONDS);
explicitWait() - Used to wait for a condition to occur on a particular element such as waiting for a specific element to be visible before interacting with it. To implement explicit wait, you need to create an object (example, wait) of the WebDriverWait class and pass the driver and wait time as parameters. You should also import the WebDriverWait library into the code. The WebDriverWait checks the condition as well as perform actions such as locating element. Therefore, you do not need to use findElement method along side it.
Syntax: WebDriverWait wait = new WebDriverWait (driver, 20); wait.until(ExpectedConditions.VisibilityofElementLocated(By.xpath(""//button[@value='Save Changes']"")));
Select commands for Handling Dropdown Menu
WebElement DropDown = driver.findElement(By.id("dropDownText"));
Select dropdown = new Select(DropDown );
Create a variable (DropDown) of type WebElement and locate the drop down menu field with id dropDownText (you can locate the menu field by any other means) and save it into the variable DropDown (or use any name of your choice). Next create an object of Select class with object name dropdown (or any name of your choice) and pass the variable (DropDown) as parameter.
selectByVisibleText(“text”); - Used to select from dropdown menu by its visible text.
selectByIndex(index); - Used to select from dropdown menu by its index number
deselectByValue(“value”); Used to select from dropdown menu by its value
Alert class command for handling Alert
In handling alert, create an instance of the Alert class object (alert) and import the Alert class library into the code. Then use the object created to access the various Alert methods. The switchTo().alert() method chaining will switch the focus from the main window to the alert window.
Alert alert = (Alert) driver.switchTo().alert();
alert.accept(); - Used to accept the alert by clicking on the alert OK button
Alert.dismiss(); - used to dismiss the alert by clicking on the dismiss button.
Scroll by pixel: This allows a webpage to be scroll to a desired pixel
Scroll to visibility of element: This allows a webpage to be scroll to a specific element.
scroll.executeScript("window.scrollBy(0,500)") - Scroll from 0 pixel to 500 pixel.
scroll.executeScript("arguments.scrollIntoView();",Element ); - scroll till element is found. Element is first located and stored in variable of type WebElement, as in
WebElement Element = driver.findElement(By.id(“id name”);
WebElement class must be imported into code.
scroll.executeScript("window.scrollTo(0, document.body.scrollHeight)"); - scroll to end of webpage
Commands to Switch Between Browser Tabs
To perform browser tab switch, first navigate to a webpage then get the page handle and save in a variable.
String oldTab = driver.getWindowHandle();
Next click on a link that opens in a new tab
driver.findElement(By.linkText("Twitter Advertising Blog")).click();
Next create an array variable (NewTab) and store the handle of the new tab
ArrayList<String> newTab = new ArrayList<String>(driver.getWindowHandles());
Next switch between tabs using the switchTo() methods
Commands to Handle and Switch Between Webpage Frames
A webpage frame can be switched to in three ways:
By Name or Id
By Web Element
iFrame index starts from 0 so we can right-click and inspect the page source to identify the iFrame number we wish to switch to, as in
We can also switch to iFrame by id or name. We first need to inspect and identify the id or name of the iFrame and then switch to it. Assuming the iFrame id is iframe1, then
To return to the main or parent frame we can use the commands:
Action Class Commands
The methods of the Action class can be used to perform the following actions:
Drag and Drop
The Action class moveToElement() method is used to implement mouse actions. To implement the mouse action, we first instantiate the Action class
Actions actions = new Actions(driver);
Next, we locate the element we want to move to and save it in a variable (targetElement) of type WebElement.
WebElement targetElement = driver.findElement(By.id(“id of element”));
Next, we need to invoke the perform() method to move to the element, passing the element name as argument.
To hover over element: actions.moveToElement(targetElement).build().perform();
To double click on element: actions.doubleClick(WebElement).build().perform();
To right click on element: actions.contextClick(WebElement).build().perform();
To drag and drop: actions.dragAndDrop(Source WebElement, Target WebElement).build().perform();
To click and hold: actions.clickAndHold(Source WebElement).moveToElement(Target WebElement).release().build().perform();
To move the slider: actions.moveToElement(WebElement).dragAndDropBy(WebElement, 300, 0).build().perform();
To resize: actions.moveToElement(WebElement).dragAndDropBy(WebElement, 100, 100).build().perform();
Test Servers to practice hands-on exercises
Volunteer SignUp Form
Mouse Right click
Drag and Drop
One of the biggest challenges faced by students who are learning how to write test scripts with Selenium WebDriver is that they often don't know where to look for a complete list of commands. When you can't find the reference guide that you need, writing test code is naturally much more difficult. That's why we've written this article: to focus on the most important topics and provide an easy-to-read reference guide for Java coding commands.
Are you ready to leap into your dream IT career? If you want to learn everything about Selenium and other tools, or you wish to have in-depth knowledge of software testing, BusyQA will help you make that possible. Our courses are easy, affordable, designed to teach you exactly what you need, and delivered in online and in-class formats. You can get started with our software testing course which covers the fundamentals of Manual, Mobile, Web Service, SQL, and Automation. Not only will you learn what you need to succeed, but you could be eligible to obtain hands-on experience with our in-house paid co-op (not guaranteed), which will help you blow the competition away. To land your dream job, click here to see our next schedule.