Selenium cheat-sheet
1 min readJun 30, 2023
Here’s a Selenium cheatsheet that provides a quick reference to common Selenium WebDriver commands and techniques:
- Importing Required Packages:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
- Setting up WebDriver:
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
WebDriver driver = new ChromeDriver();
- Navigating to a URL:
driver.get("https://www.example.com");
- 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"));
- Interacting with Elements:
element.click();
element.sendKeys("text");
element.clear();
- Working with Dropdowns:
WebElement dropdown = driver.findElement(By.id("dropdownId"));
Select select = new Select(dropdown);
select.selectByVisibleText("optionText");
select.selectByValue("optionValue");
select.selectByIndex(index);
- Working with Frames:
driver.switchTo().frame("frameName");
driver.switchTo().frame(index);
driver.switchTo().defaultContent();
- Handling Alerts:
Alert alert = driver.switchTo().alert();
alert.accept();
alert.dismiss();
alert.sendKeys("text");
alert.getText();
- 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")));
- 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…