Selenium cheat-sheet

Mayank Gupta
1 min readJun 30, 2023

--

Here’s a Selenium cheatsheet that provides a quick reference to common Selenium WebDriver commands and techniques:

  1. Importing Required Packages:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
  1. Setting up WebDriver:
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
WebDriver driver = new ChromeDriver();
  1. Navigating to a URL:
driver.get("https://www.example.com");
  1. Locating Elements:
WebElement element = driver.findElement(By.id("elementId"));
WebElement element = driver.findElement(By.name("elementName"));
WebElement element = driver.findElement(By.className("className"));
WebElement element = driver.findElement(By.tagName("tagName"));
WebElement element = driver.findElement(By.xpath("xpathExpression"));
  1. Interacting with Elements:
element.click();
element.sendKeys("text");
element.clear();
  1. Working with Dropdowns:
WebElement dropdown = driver.findElement(By.id("dropdownId"));
Select select = new Select(dropdown);
select.selectByVisibleText("optionText");
select.selectByValue("optionValue");
select.selectByIndex(index);
  1. Working with Frames:
driver.switchTo().frame("frameName");
driver.switchTo().frame(index);
driver.switchTo().defaultContent();
  1. Handling Alerts:
Alert alert = driver.switchTo().alert();
alert.accept();
alert.dismiss();
alert.sendKeys("text");
alert.getText();
  1. Waits and Synchronization:
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;

WebDriverWait wait = new WebDriverWait(driver, timeoutInSeconds);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("elementId")));
  1. Taking Screenshots:
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;

TakesScreenshot screenshot = (TakesScreenshot) driver;
File file = screenshot.getScreenshotAs(OutputType.FILE);

This cheatsheet covers some of the commonly used Selenium WebDriver commands. Keep in mind that it’s always a good practice to refer to official Selenium documentation and resources for more detailed information and examples.

For more articles consider making a follow on my account. Thanks…

--

--

Mayank Gupta
Mayank Gupta

Written by Mayank Gupta

QA Automation Lead | Web Automation | Mobile Automation | API Automation l Performance | Web Security | IOT | Blockchain

No responses yet