This comprehensive Selenium Cheat Sheet with Java serves as a quick reference guide for beginners and experienced developers working with Selenium WebDriver. It covers essential topics, including setup, basic commands, and many more.

Whether you’re looking to automate browser actions or scale tests across multiple environments, this cheat sheet equips you with practical, ready-to-use code snippets for efficient test automation.

Selenium Cheat Sheet with Java

Here are the different commands for setup, TestNG, JUnit, locators, interactions, waits, alerts, frames, dropdowns, files, navigation, and more.

Setup

Add the following Maven dependency to your pom.xml if using Maven
<dependency>
  <groupId>org.seleniumhq.selenium</groupId>
  <artifactId>selenium-java</artifactId>
  <version>4.x.x</version>
</dependency>

WebDriver Setup

Chrome
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver();
Firefox
System.setProperty("webdriver.gecko.driver", "path/to/geckodriver"); WebDriver driver = new FirefoxDriver();
Microsoft Edge
System.setProperty("webdriver.edge.driver", "path/to/msedgedriver"); WebDriver driver = new EdgeDriver();
Safari (Only Mac)
WebDriver driver = new SafariDriver();

TestNG

@BeforeSuite Runs before the execution of all the test methods in the suite
@BeforeTest Executes before the execution of all the test methods of available classes belonging to that folder
@BeforeClass Executes before the first method of the current class is invoked
@BeforeMethod Executes before each test method runs
@Test This is the main part of our automation script, where we will write the business logic we want to automate.
@AfterMethod Executes after the execution of each test method.
@AfterClass Executes after the execution of all the test methods of the current class.
@AfterTest Executes after the execution of all the test methods of available classes belonging to that folder.
@AfterSuite Executes after the execution of all the test methods in the suite.

JUnit

@Test Represents the method or class as a test block and also accepts parameters.
@Before The method with this annotation gets executed before all the other tests.
@BeforeClass The method with this annotation gets executed once before the class.
@After The method with this annotation gets executed after all the other tests are executed.
@AfterClass The method with this annotation gets executed once after class.
@Ignore It is used to ignore a few test statements during execution.
@Disabled Used to disable the tests from execution, but the corresponding reports of the tests are still generated.

Basic Commands

Launch Browser
driver.get("https://example.com");
Get Page Title
String title = driver.getTitle();
System.out.println("Title: " + title);
Get Current URL
String url = driver.getCurrentUrl();
Close Browser
driver.close(); // Closes the current window
driver.quit(); // Closes all windows and ends the session
Sleep
Thread.sleep(<Time in MilliSeconds>);

Locators

By ID
WebElement element = driver.findElement(By.id("elementId"));
By Name
WebElement element = driver.findElement(By.name("elementName"));
By Class Name
WebElement element = driver.findElement(By.className("className"));
By Tag Name
WebElement element = driver.findElement(By.tagName("tagName"));
By Link Text
WebElement element = driver.findElement(By.linkText("Link Text"));
By Partial Link Text
WebElement element = driver.findElement(By.partialLinkText("Partial Text"));
By CSS Selector
WebElement element = driver.findElement(By.cssSelector("cssSelector"));
By XPath
WebElement element = driver.findElement(By.xpath("xpathExpression"));

Interactions

Click an Element
element.click();
Type Text
element.sendKeys("Input text");
Clear Text
element.clear();
Submit a Form
element.submit();

Waits

Implicit Wait
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
Explicit Wait
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("elementId")));

Handling Alerts

Switch to Alert
Alert alert = driver.switchTo().alert();
Accept Alert
alert.accept();
Dismiss Alert
alert.dismiss();
Get Alert Text
String alertText = alert.getText();

Handling Frames

Switch to a Frame
driver.switchTo().frame("frameNameOrId");
Switch to a Frame by Name or ID
driver.switchTo().frame("buttonframe");
Switch to a Frame by Index
driver.switchTo().frame(1);
Switch to a Frame using a WebElement
WebElement iframe = driver.findElement(By.cssSelector("#modal>iframe"));
driver.switchTo().frame(iframe);
Switch to Parent Frame
driver.switchTo().parentFrame();
Switch to Default Content
driver.switchTo().defaultContent();

Handling Dropdowns

Select by Visible Text
Select select = new Select(driver.findElement(By.id("dropdownId")));
select.selectByVisibleText("Option Text");
Select by Index
select.selectByIndex(1);
Select by Value
select.selectByValue("optionValue");

Browser Navigation

Navigate to URL
driver.navigate().to("https://example.com");
Back
driver.navigate().back();
Forward
driver.navigate().forward();
Refresh Page
driver.navigate().refresh();

Browser Window Management

Get the Current Window Handle
String mainWindowHandle = driver.getWindowHandle();
Get All Window Handles
import java.util.Set;
Set<String> allWindowHandles = driver.getWindowHandles();
Switch to a Specific Window
String windowHandle = driver.getWindowHandle();
driver.switchTo().window(windowHandle);
Switch to the Newly Created Window
driver.switchTo().newWindow(WindowType.TAB);
driver.switchTo().newWindow(WindowType.WINDOW);
Fullscreen Window
driver.manage().window().fullscreen();
Minimize Window
driver.manage().window().minimize();
Maximize Window
driver.manage().window().maximize();
Get Window Size
Dimension size = driver.manage().window().getSize();
Set Window Position
driver.manage().window().setPosition(new Point(0, 0));

Cookies

Add Cookie
Cookie cookie = new Cookie("key", "value"); driver.manage().addCookie(cookie);
Get All Cookies
Set<Cookie> cookies = driver.manage().getCookies();
Delete Cookie
driver.manage().deleteCookieNamed("key");

Taking Screenshot

Full Page
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("path/to/screenshot.png"));
WebElement Screenshot
File elementScreenshot = element.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(elementScreenshot, new File("path/to/element_screenshot.png"));

Working with Files

Upload a File
driver.findElement(By.id("file-upload")).sendKeys(“path/to/your/file.txt”);
driver.findElement(By.id("file-submit")).submit();
Read Data from a Text File
Using BufferedReader
FileReader reader = new FileReader("MyFile.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
  System.out.println(line);
}
reader.close();
Using InputStream
FileInputStream inputStream = new FileInputStream("MyFile.txt");
InputStreamReader reader = new InputStreamReader(inputStream, "UTF-16");
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
reader.close();
Using FileReader
FileReader reader = new FileReader("MyFile.txt");
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
reader.close();
Read Data from a CSV File
import au.com.bytecode.opencsv.CSVReader;
String path = "C:\\Users\\Avinash\\Desktop\\csvtest.csv";
Reader reader = new FileReader(path);
CSVReader csvreader = new CSVReader(reader);
List<String[]> data = csvreader.readAll();
for(String[] d : data){
  for(String c : d ){
    System.out.println(c);
  }
}
Read Data from an Excel File
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

File file = new File("E:\\TestData\\TestData.xls");
FileInputStream inputStream = new FileInputStream(file);

HSSFWorkbook wb=new HSSFWorkbook(inputStream);
HSSFSheet sheet=wb.getSheet("STUDENT_DATA");
HSSFRow row2=sheet.getRow(1);
HSSFCell cell=row2.getCell(5);

String address= cell.getStringCellValue();

JavaScript Execution

Execute JavaScript
JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("window.scrollBy(0,1000);");
Disable a Field (set the ‘disabled’ attribute)
JavascriptExecutor javascript = (JavascriptExecutor) driver;
String todisable = "document.getElementsByName('fname')[0].setAttribute('disabled', '');";
javascript.executeScript(todisable);
Enable a Field (remove the ‘disabled’ attribute)
JavascriptExecutor javascript = (JavascriptExecutor) driver;
String toEnable = "document.getElementsByName('fname')[0].setAttribute(enabled, '');";
javascript.executeScript(toEnable);

Selenium Grid

Start Hub
java -jar selenium-server-4.x.x.jar hub
Start Node
java -jar selenium-server-4.x.x.jar node --detect-drivers true
Server
http://localhost:4444/ui

We hope that you will find this Selenium commands cheat sheet useful in your testing journey!