LearnThatStack Ace your next interview
Testing · Free

Selenium.
Interview cheat sheet.

Quick reference for Selenium - sectioned for fast scanning. Skim the part you're shaky on, walk in confident.

Testing 20-section reference ~5 min read

Summary

Selenium WebDriver automates web browser interactions for testing web applications across multiple browsers and platforms. Master locator strategies, waits, element interactions, Page Object Model, and framework integration to build robust, maintainable test automation suites that ensure web application quality.

1. Introduction & Architecture

What is Selenium?

  • Open-source automation testing framework for web applications
  • Supports multiple browsers, platforms, and programming languages
  • Components: Selenium IDE, WebDriver, Grid

Selenium WebDriver Architecture

Test Script → WebDriver API → Browser Driver → Browser

2. Setup & Basic Configuration

Maven Dependencies (Java)

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

Basic Setup

// Chrome
WebDriver driver = new ChromeDriver();

// Firefox
WebDriver driver = new FirefoxDriver();

// Edge
WebDriver driver = new EdgeDriver();

3. Locator Strategies

8 Types of Locators (Priority Order)

  1. ID - Fastest and most reliable
driver.findElement(By.id("email"));
  1. Name
driver.findElement(By.name("username"));
  1. Class Name
driver.findElement(By.className("btn-primary"));
  1. Tag Name
driver.findElement(By.tagName("input"));
  1. Link Text
driver.findElement(By.linkText("Sign Up"));
  1. Partial Link Text
driver.findElement(By.partialLinkText("Sign"));
  1. CSS Selector - Flexible and fast
// ID: #id
driver.findElement(By.cssSelector("#email"));
// Class: .class
driver.findElement(By.cssSelector(".submit-btn"));
// Attribute: [attribute='value']
driver.findElement(By.cssSelector("input[type='text']"));
// Multiple attributes
driver.findElement(By.cssSelector("input[type='text'][name='user']"));
  1. XPath - Most flexible but slower
// Absolute XPath (avoid)
driver.findElement(By.xpath("/html/body/div[1]/form/input"));

// Relative XPath (preferred)
driver.findElement(By.xpath("//input[@id='email']"));

// XPath with text
driver.findElement(By.xpath("//button[text()='Submit']"));

// XPath with contains
driver.findElement(By.xpath("//button[contains(@class,'submit')]"));
driver.findElement(By.xpath("//button[contains(text(),'Submit')]"));

// XPath axes
driver.findElement(By.xpath("//label[@for='email']/following-sibling::input"));

4. Essential WebDriver Methods

driver.get("https://example.com");
driver.navigate().to("https://example.com");
driver.navigate().back();
driver.navigate().forward();
driver.navigate().refresh();

Window Management

driver.manage().window().maximize();
driver.manage().window().minimize();
driver.manage().window().fullscreen();
driver.manage().window().setSize(new Dimension(1024, 768));

Getting Information

String title = driver.getTitle();
String url = driver.getCurrentUrl();
String pageSource = driver.getPageSource();
String windowHandle = driver.getWindowHandle();
Set<String> windowHandles = driver.getWindowHandles();

5. WebElement Operations

Basic Operations

WebElement element = driver.findElement(By.id("input"));

// Input operations
element.sendKeys("text");
element.clear();
element.submit();

// Click
element.click();

// Get information
String text = element.getText();
String value = element.getAttribute("value");
String tagName = element.getTagName();
Dimension size = element.getSize();
Point location = element.getLocation();

// State checks
boolean displayed = element.isDisplayed();
boolean enabled = element.isEnabled();
boolean selected = element.isSelected();

6. Waits in Selenium

Implicit Wait

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

Explicit Wait

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

// Wait for element to be clickable
WebElement element = wait.until(
    ExpectedConditions.elementToBeClickable(By.id("submit"))
);

// Common Expected Conditions
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("msg")));
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("elem")));
wait.until(ExpectedConditions.alertIsPresent());
wait.until(ExpectedConditions.titleContains("Dashboard"));
wait.until(ExpectedConditions.urlContains("/home"));
wait.until(ExpectedConditions.numberOfWindowsToBe(2));

Fluent Wait

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
    .withTimeout(Duration.ofSeconds(30))
    .pollingEvery(Duration.ofSeconds(5))
    .ignoring(NoSuchElementException.class);

WebElement element = wait.until(driver -> 
    driver.findElement(By.id("dynamic-element"))
);

7. Handling Different Elements

Select dropdown = new Select(driver.findElement(By.id("country")));

// Select options
dropdown.selectByIndex(1);
dropdown.selectByValue("USA");
dropdown.selectByVisibleText("United States");

// Get options
List<WebElement> options = dropdown.getOptions();
WebElement firstSelected = dropdown.getFirstSelectedOption();
List<WebElement> allSelected = dropdown.getAllSelectedOptions();

// Deselect (only for multi-select)
dropdown.deselectAll();
dropdown.deselectByIndex(1);

Checkboxes and Radio Buttons

WebElement checkbox = driver.findElement(By.id("terms"));
if (!checkbox.isSelected()) {
    checkbox.click();
}

Alerts

// Switch to alert
Alert alert = driver.switchTo().alert();

// Alert operations
String alertText = alert.getText();
alert.accept();        // Click OK
alert.dismiss();       // Click Cancel
alert.sendKeys("text"); // Enter text in prompt

Frames/iFrames

// Switch to frame
driver.switchTo().frame(0); // By index
driver.switchTo().frame("frameName"); // By name or ID
driver.switchTo().frame(frameElement); // By WebElement

// Switch back
driver.switchTo().defaultContent();
driver.switchTo().parentFrame();

Windows/Tabs

// Store original window
String originalWindow = driver.getWindowHandle();

// Switch to new window
for (String windowHandle : driver.getWindowHandles()) {
    if (!originalWindow.equals(windowHandle)) {
        driver.switchTo().window(windowHandle);
        break;
    }
}

// Switch back
driver.switchTo().window(originalWindow);

8. Actions Class (Advanced Interactions)

Actions actions = new Actions(driver);

// Mouse actions
actions.moveToElement(element).perform();
actions.clickAndHold(element).perform();
actions.doubleClick(element).perform();
actions.contextClick(element).perform(); // Right-click
actions.dragAndDrop(source, target).perform();

// Keyboard actions
actions.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).perform();
actions.sendKeys(Keys.ENTER).perform();

// Combined actions
actions.moveToElement(element)
       .click()
       .sendKeys("text")
       .doubleClick()
       .build()
       .perform();

9. JavaScript Executor

JavascriptExecutor js = (JavascriptExecutor) driver;

// Scroll operations
js.executeScript("window.scrollBy(0,500)");
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
js.executeScript("arguments[0].scrollIntoView(true);", element);

// Click element
js.executeScript("arguments[0].click();", element);

// Get value
String value = (String) js.executeScript("return arguments[0].value;", element);

// Set attribute
js.executeScript("arguments[0].setAttribute('value','text')", element);

// Highlight element (useful for debugging)
js.executeScript("arguments[0].style.border='3px solid red'", element);

10. Screenshots & File Upload

Screenshots

// Full page screenshot
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("screenshot.png"));

// Element screenshot (Selenium 4+)
File elementScreenshot = element.getScreenshotAs(OutputType.FILE);

File Upload

WebElement uploadElement = driver.findElement(By.id("upload"));
uploadElement.sendKeys("/path/to/file.txt");

11. Test Frameworks Integration

TestNG Annotations

@BeforeSuite, @AfterSuite
@BeforeTest, @AfterTest
@BeforeClass, @AfterClass
@BeforeMethod, @AfterMethod
@Test(priority=1, enabled=true, groups={"smoke"})
@DataProvider
@Parameters

Page Object Model (POM)

public class LoginPage {
    WebDriver driver;
    
    // Constructor
    public LoginPage(WebDriver driver) {
        this.driver = driver;
        PageFactory.initElements(driver, this);
    }
    
    // Page Factory
    @FindBy(id = "username")
    WebElement usernameField;
    
    @FindBy(id = "password")
    WebElement passwordField;
    
    @FindBy(id = "login")
    WebElement loginButton;
    
    // Methods
    public void login(String user, String pass) {
        usernameField.sendKeys(user);
        passwordField.sendKeys(pass);
        loginButton.click();
    }
}

12. Selenium Grid

Grid Setup

# Start Hub
java -jar selenium-server.jar hub

# Start Node
java -jar selenium-server.jar node --hub http://localhost:4444

Remote WebDriver

DesiredCapabilities caps = new DesiredCapabilities();
caps.setBrowserName("chrome");
caps.setPlatform(Platform.WINDOWS);

WebDriver driver = new RemoteWebDriver(
    new URL("http://localhost:4444/wd/hub"), 
    caps
);

13. Best Practices

1. Use Explicit Waits over Implicit Waits

  • More reliable and specific
  • Better performance

2. Prefer CSS Selectors over XPath

  • Faster execution
  • More readable

3. Use Page Object Model

  • Better maintainability
  • Reusable code

4. Avoid Hard-coded Values

// Bad
Thread.sleep(5000);

// Good
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.elementToBeClickable(element));

5. Handle Exceptions Properly

try {
    element.click();
} catch (StaleElementReferenceException e) {
    element = driver.findElement(By.id("element"));
    element.click();
}

14. Critical Interview Scenarios

Handling Dynamic Elements

// Use dynamic XPath
driver.findElement(By.xpath("//div[contains(@id,'dynamic_')]"));

// Use explicit wait
wait.until(ExpectedConditions.presenceOfElementLocated(locator));

Multiple Window Management

String mainWindow = driver.getWindowHandle();
Set<String> windows = driver.getWindowHandles();

for (String window : windows) {
    if (!window.equals(mainWindow)) {
        driver.switchTo().window(window);
        // Perform actions
        driver.close();
    }
}
driver.switchTo().window(mainWindow);

Element State Verification

// Present in DOM
boolean present = driver.findElements(By.id("element")).size() > 0;

// Visible on page
boolean displayed = element.isDisplayed();

Ajax Call Synchronization

// Wait for Ajax to complete
wait.until(new ExpectedCondition<Boolean>() {
    public Boolean apply(WebDriver driver) {
        return ((JavascriptExecutor)driver)
            .executeScript("return jQuery.active == 0");
    }
});

Data-Driven Testing Implementation

@DataProvider(name = "loginData")
public Object[][] getData() {
    return new Object[][] {
        {"user1", "pass1"},
        {"user2", "pass2"}
    };
}

@Test(dataProvider = "loginData")
public void testLogin(String username, String password) {
    // Test implementation
}

15. Selenium 4 New Features

Relative Locators

// Find element relative to another
driver.findElement(RelativeLocator.with(By.tagName("input"))
    .above(By.id("password"))
    .below(By.id("email")));

New Window/Tab

// Open new window
driver.switchTo().newWindow(WindowType.WINDOW);

// Open new tab
driver.switchTo().newWindow(WindowType.TAB);

Chrome DevTools Protocol

ChromeDriver driver = new ChromeDriver();
DevTools devTools = driver.getDevTools();
devTools.createSession();

// Network interception
devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));

16. Common Exceptions

  1. NoSuchElementException - Element not found
  2. StaleElementReferenceException - Element no longer attached to DOM
  3. TimeoutException - Wait condition not met
  4. ElementNotInteractableException - Element not clickable/visible
  5. NoSuchWindowException - Window not found
  6. NoAlertPresentException - No alert present
  7. InvalidSelectorException - Invalid CSS/XPath selector

17. Performance Tips

  • Use CSS selectors for better performance
  • Minimize use of Thread.sleep()
  • Close unnecessary windows/tabs
  • Use headless mode for faster execution
  • Implement proper wait strategies
  • Reuse browser instances when possible

18. Debugging Tips

  • Take screenshots on failure
  • Use browser developer tools
  • Add logging statements
  • Highlight elements with JavaScript
  • Use breakpoints in IDE
  • Check element state before interaction

Interview Success Tips

Technical Proficiency

  • Locator Strategy: Prioritize ID > CSS > XPath for performance
  • Wait Mechanisms: Explicit waits over implicit, avoid Thread.sleep()
  • Page Object Model: Demonstrate maintainable test architecture
  • Framework Integration: TestNG/JUnit annotations, reporting
  • Cross-Browser Testing: Chrome, Firefox, Edge compatibility

Best Practices to Demonstrate

  • Reusable Components: Base classes, utility methods
  • Error Handling: StaleElementReference, NoSuchElement exceptions
  • Parallel Execution: Thread-safe test design
  • CI/CD Integration: Jenkins, GitHub Actions experience
  • Version Compatibility: WebDriver and browser version management

Common Pitfalls to Avoid

  • Hard-coded waits instead of dynamic waits
  • Absolute XPath instead of relative
  • Not handling alerts and pop-ups
  • Ignoring browser console errors
  • Poor test data management

Key Points to Remember

  • WebDriver follows W3C protocol standards
  • Selenium 4 includes relative locators and DevTools integration
  • Grid enables distributed test execution
  • Always close browser sessions properly
  • Keep WebDriver and browser versions synchronized
Found this useful? Pass it on.
Pro · $10/mo

The sheet is free. Pro goes deeper.

Pro opens the full question library behind every sheet, every refresher and a monthly AI allowance. One subscription, all formats.

Full question library All refreshers Cancel anytime