logo
eng-flag

Selenium Cheatsheet

Table of Contents

  1. Installation and Setup
  2. WebDriver Setup
  3. Basic Commands
  4. Locators
  5. Waits
  6. Actions
  7. Assertions
  8. Handling Alerts and Popups
  9. Working with Frames and Windows
  10. Advanced Techniques
  11. Best Practices

Installation and Setup

Installing Selenium

To install Selenium for Python, use pip:

pip install selenium

For Java, add this to your pom.xml (Maven):

<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>4.10.0</version>
</dependency>

WebDriver Setup

Python

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))

Java

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;

WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();

Basic Commands

Open a webpage

driver.get("https://www.example.com")
driver.get("https://www.example.com");

Get current URL

current_url = driver.current_url
String currentUrl = driver.getCurrentUrl();

Get page title

title = driver.title
String title = driver.getTitle();

Close browser

driver.quit()
driver.quit();

Locators

By ID

element = driver.find_element(By.ID, "myElementId")
WebElement element = driver.findElement(By.id("myElementId"));

By Name

element = driver.find_element(By.NAME, "myElementName")
WebElement element = driver.findElement(By.name("myElementName"));

By Class Name

element = driver.find_element(By.CLASS_NAME, "myClassName")
WebElement element = driver.findElement(By.className("myClassName"));

By CSS Selector

element = driver.find_element(By.CSS_SELECTOR, "#myId > div.class")
WebElement element = driver.findElement(By.cssSelector("#myId > div.class"));

By XPath

element = driver.find_element(By.XPATH, "//input[@name='username']")
WebElement element = driver.findElement(By.xpath("//input[@name='username']"));

Waits

Implicit Wait

driver.implicitly_wait(10)  # seconds
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

Explicit Wait

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

element = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "myElementId"))
)
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;

WebElement element = new WebDriverWait(driver, Duration.ofSeconds(10))
        .until(ExpectedConditions.presenceOfElementLocated(By.id("myElementId")));

Actions

Click

element.click()
element.click();

Send Keys

element.send_keys("Hello, World!")
element.sendKeys("Hello, World!");

Clear

element.clear()
element.clear();

Submit Form

element.submit()
element.submit();

Assertions

Python (using unittest)

import unittest

class MyTest(unittest.TestCase):
    def test_title(self):
        self.assertEqual(driver.title, "Expected Title")

    def test_element_text(self):
        element = driver.find_element(By.ID, "myElementId")
        self.assertEqual(element.text, "Expected Text")

    def test_element_attribute(self):
        element = driver.find_element(By.ID, "myElementId")
        self.assertEqual(element.get_attribute("class"), "expected-class")

Java (using JUnit)

import org.junit.Assert;

public class MyTest {
    @Test
    public void testTitle() {
        Assert.assertEquals("Expected Title", driver.getTitle());
    }

    @Test
    public void testElementText() {
        WebElement element = driver.findElement(By.id("myElementId"));
        Assert.assertEquals("Expected Text", element.getText());
    }

    @Test
    public void testElementAttribute() {
        WebElement element = driver.findElement(By.id("myElementId"));
        Assert.assertEquals("expected-class", element.getAttribute("class"));
    }
}

Handling Alerts and Popups

Accept Alert

alert = driver.switch_to.alert
alert.accept()
Alert alert = driver.switchTo().alert();
alert.accept();

Dismiss Alert

alert = driver.switch_to.alert
alert.dismiss()
Alert alert = driver.switchTo().alert();
alert.dismiss();

Get Alert Text

alert = driver.switch_to.alert
alert_text = alert.text
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();

Working with Frames and Windows

Switch to Frame

# By index
driver.switch_to.frame(0)

# By name or ID
driver.switch_to.frame("frameName")

# By WebElement
frame_element = driver.find_element(By.TAG_NAME, "iframe")
driver.switch_to.frame(frame_element)
// By index
driver.switchTo().frame(0);

// By name or ID
driver.switchTo().frame("frameName");

// By WebElement
WebElement frameElement = driver.findElement(By.tagName("iframe"));
driver.switchTo().frame(frameElement);

Switch to Window

# Switch to new window
original_window = driver.current_window_handle
for window_handle in driver.window_handles:
    if window_handle != original_window:
        driver.switch_to.window(window_handle)
        break
// Switch to new window
String originalWindow = driver.getWindowHandle();
for (String windowHandle : driver.getWindowHandles()) {
    if(!originalWindow.contentEquals(windowHandle)) {
        driver.switchTo().window(windowHandle);
        break;
    }
}

Advanced Techniques

Execute JavaScript

js_code = "return document.title;"
title = driver.execute_script(js_code)
String jsCode = "return document.title;";
String title = (String) ((JavascriptExecutor) driver).executeScript(jsCode);

Take Screenshot

driver.save_screenshot("screenshot.png")
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
Files.copy(screenshot.toPath(), Paths.get("screenshot.png"));

Handle File Upload

file_input = driver.find_element(By.ID, "fileInput")
file_input.send_keys("/path/to/file.txt")
WebElement fileInput = driver.findElement(By.id("fileInput"));
fileInput.sendKeys("/path/to/file.txt");

Best Practices

  1. Use explicit waits instead of implicit waits or Thread.sleep()
  2. Utilize Page Object Model for better test organization
  3. Use CSS Selectors or ID locators when possible for better performance
  4. Avoid XPath when possible, as it can be slow and brittle
  5. Keep tests independent and avoid dependencies between tests
  6. Clean up resources after tests (close browser, quit WebDriver)
  7. Use headless mode for faster test execution in CI/CD pipelines
  8. Implement logging for better debugging
  9. Use configuration files for environment-specific settings
  10. Regularly update Selenium and WebDriver to the latest stable versions

2024 © All rights reserved - buraxta.com