SE
Java

Selenium Java Cheat Sheet

COMPLETE REFERENCE · WEBDRIVER · LOCATORS · WAITS · FRAMEWORKS · TESTNG

🎓 Next Gen QA IT Coaching Classes
📞 Mr. Khan Sir  |  8700350994
Online & Offline B.Tech / BCA / MCA CBSE · ICSE · Polytechnic Software Testing
Setup & WebDriver Launch · Browser · Navigation · Driver Info
Maven Dependencies (pom.xml)
Selenium Java dependency
<!-- pom.xml --> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.18.1</version> </dependency> <!-- WebDriverManager --> <dependency> <groupId>io.github.bonigarcia</groupId> <artifactId>webdrivermanager</artifactId> <version>5.8.0</version> </dependency>
TestNG dependency
<dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>7.9.0</version> <scope>test</scope> </dependency>
Browser Launch — WebDriverManager
Launch Chrome (recommended)
// Auto manages chromedriver WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver();
Launch Chrome with options
ChromeOptions options = new ChromeOptions(); options.addArguments("--headless"); options.addArguments("--maximize"); options.addArguments("--incognito"); WebDriver driver = new ChromeDriver(options);
Launch Firefox / Edge
WebDriverManager.firefoxdriver().setup(); WebDriver driver = new FirefoxDriver(); WebDriverManager.edgedriver().setup(); WebDriver driver = new EdgeDriver();
Navigation Commands
Open URL / back / forward / refresh
driver.get("https://example.com"); driver.navigate().to("https://example.com"); driver.navigate().back(); driver.navigate().forward(); driver.navigate().refresh();
Browser window controls
driver.manage().window().maximize(); driver.manage().window().minimize(); driver.manage().window().fullscreen(); // Set specific size driver.manage().window() .setSize(new Dimension(1280, 720));
Get browser info
String url = driver.getCurrentUrl(); String title = driver.getTitle(); String src = driver.getPageSource();
Close & Quit
Close current window / quit all
// Close current active window driver.close(); // Quit — closes ALL windows driver.quit();
Implicit wait / Page load timeout
// Set implicit wait globally driver.manage().timeouts() .implicitlyWait( Duration.ofSeconds(10)); // Page load timeout driver.manage().timeouts() .pageLoadTimeout( Duration.ofSeconds(30)); // Script timeout driver.manage().timeouts() .scriptTimeout( Duration.ofSeconds(5));
Locators · findElement / findElements · WebElement Actions
All Locator Strategies — By
8 locator types with examples
// 1. By ID — fastest & most reliable driver.findElement(By.id("username")); // 2. By Name driver.findElement(By.name("email")); // 3. By Class Name driver.findElement(By.className("btn-primary")); // 4. By Tag Name driver.findElement(By.tagName("input")); // 5. By Link Text (exact match) driver.findElement(By.linkText("Click Here")); // 6. By Partial Link Text driver.findElement(By.partialLinkText("Click")); // 7. By CSS Selector driver.findElement(By.cssSelector("#id .class")); // 8. By XPath driver.findElement(By.xpath("//input[@id='user']"));
CSS Selector — Complete Guide
All CSS selector patterns
// By ID By.cssSelector("#username") // By Class By.cssSelector(".btn-login") // Tag + ID By.cssSelector("input#email") // Tag + Class By.cssSelector("button.primary") // Attribute exact match By.cssSelector("input[type='text']") // Attribute starts with By.cssSelector("a[href^='https']") // Attribute ends with By.cssSelector("a[href$='.pdf']") // Attribute contains By.cssSelector("input[name*='user']") // Child element By.cssSelector("div > p") // Descendant element By.cssSelector("div p") // nth-child By.cssSelector("tr:nth-child(2)")
XPath — Complete Guide
Absolute vs Relative & all patterns
// Absolute XPath (not recommended) /html/body/div/form/input[1] // Relative XPath (recommended) //input[@id='username'] // By attribute //input[@type='text'] //button[@name='login'] // By text content //button[text()='Login'] //a[text()='Click Here'] // Contains — partial match //input[contains(@id,'user')] //div[contains(text(),'Welcome')] // Starts-with //input[starts-with(@name,'em')] // AND / OR conditions //input[@type='text' and @name='user'] //input[@id='u' or @id='un'] // Parent / Following-sibling //label[text()='Email']/following-sibling::input //input[@id='user']/parent::div // Axes — ancestor / descendant //div[@class='form']//input //tr[td[text()='Khan']]
findElement vs findElements
Single element vs list of elements
// findElement — returns 1 WebElement // throws NoSuchElementException if not found WebElement el = driver .findElement(By.id("username")); // findElements — returns List<WebElement> // returns empty list if not found List<WebElement> els = driver .findElements(By.tagName("a")); // Check if element exists boolean exists = driver .findElements(By.id("msg")).size() > 0; // Loop through all elements for (WebElement e : els) { System.out.println(e.getText()); }
Get element properties
el.getText() el.getAttribute("href") el.getAttribute("value") el.getCssValue("color") el.getTagName() el.getSize() // width & height el.getLocation() // x & y on page el.isDisplayed() // visible? el.isEnabled() // enabled? el.isSelected() // checked/selected?
WebElement Actions · Form Interactions · Dropdowns · Checkboxes · Radio
Basic WebElement Actions
Click / Type / Clear / Submit
// Click an element driver.findElement(By.id("btn")).click(); // Type into input field driver.findElement(By.id("user")) .sendKeys("khanSir@qa.com"); // Clear input field driver.findElement(By.id("user")).clear(); // Clear then type WebElement inp = driver .findElement(By.id("email")); inp.clear(); inp.sendKeys("test@nextgenqa.com"); // Submit a form driver.findElement(By.id("form")) .submit(); // Send special keys inp.sendKeys(Keys.ENTER); inp.sendKeys(Keys.TAB); inp.sendKeys(Keys.BACK_SPACE); inp.sendKeys(Keys.chord(Keys.CONTROL,"a")); inp.sendKeys(Keys.chord(Keys.CONTROL,"c"));
Dropdown — Select Class
All Select operations
// Import: org.openqa.selenium.support.ui.Select WebElement ddEl = driver .findElement(By.id("course")); Select dd = new Select(ddEl); // Select by visible text dd.selectByVisibleText("Manual Testing"); // Select by value attribute dd.selectByValue("selenium"); // Select by index (0-based) dd.selectByIndex(2); // Get selected option text String selected = dd .getFirstSelectedOption().getText(); // Get all options List<WebElement> opts = dd.getOptions(); // Multi-select — deselect dd.deselectByIndex(0); dd.deselectAll(); // Check if multi-select boolean isMulti = dd.isMultiple();
Checkbox & Radio Button
Check / uncheck / verify state
WebElement chk = driver .findElement(By.id("agree")); // Check if already selected boolean isChecked = chk.isSelected(); // Check the checkbox if (!chk.isSelected()) { chk.click(); } // Uncheck the checkbox if (chk.isSelected()) { chk.click(); }
Radio button selection
// Select a radio button driver.findElement( By.xpath("//input[@value='online']") ).click(); // Get all radio buttons in group List<WebElement> radios = driver .findElements( By.name("classMode")); for (WebElement r : radios) { if (r.getAttribute("value") .equals("offline")) { r.click(); break; } }
Actions Class — Mouse & Keyboard
Complex interactions using Actions
// Import: org.openqa.selenium.interactions.Actions Actions act = new Actions(driver); // Mouse hover act.moveToElement(element).perform(); // Right click (context menu) act.contextClick(element).perform(); // Double click act.doubleClick(element).perform(); // Drag and drop act.dragAndDrop(source, target) .perform(); // Drag by offset act.dragAndDropBy(el, 100, 200) .perform(); // Click and hold act.clickAndHold(element).perform(); // Key down + click (multi-select) act.keyDown(Keys.CONTROL) .click(el1).click(el2) .keyUp(Keys.CONTROL) .perform(); // Scroll to element act.scrollToElement(element).perform(); // Chain multiple actions act.moveToElement(menu) .click() .moveToElement(subMenu) .click() .perform();
Explicit Wait · Implicit Wait · Fluent Wait · ExpectedConditions
Implicit Wait
Global wait — applies to all findElements
// Set once — applies globally // Waits up to 10s for element to appear driver.manage().timeouts() .implicitlyWait( Duration.ofSeconds(10)); // ⚠️ Do NOT mix implicit + explicit! // Use only one type in your project
Fluent Wait
Poll every N seconds, ignore exceptions
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver) .withTimeout( Duration.ofSeconds(30)) .pollingEvery( Duration.ofSeconds(2)) .ignoring( NoSuchElementException.class); WebElement el = wait.until(d -> d.findElement( By.id("submitBtn")));
Explicit Wait — WebDriverWait
Wait for specific condition
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); // Wait until element is visible WebElement el = wait.until( ExpectedConditions .visibilityOfElementLocated( By.id("result"))); // Wait until clickable wait.until( ExpectedConditions .elementToBeClickable( By.id("submitBtn"))); // Wait for URL to contain wait.until( ExpectedConditions .urlContains("dashboard")); // Wait for title wait.until( ExpectedConditions .titleContains("Home"));
All ExpectedConditions
Complete list of conditions
// Element presence (in DOM, may not be visible) .presenceOfElementLocated(By) // Element visible on page .visibilityOfElementLocated(By) // Element invisible / hidden .invisibilityOfElementLocated(By) // Element clickable (visible + enabled) .elementToBeClickable(By) // Text present in element .textToBePresentInElementLocated(By, "text") // Attribute contains value .attributeContains(By, "class", "active") // Element selected (checkbox/radio) .elementToBeSelected(element) // Alert is present .alertIsPresent() // Frame available to switch .frameToBeAvailableAndSwitchToIt(By) // Number of windows = N .numberOfWindowsToBe(2) // URL contains / matches .urlContains("dashboard") .urlToBe("https://example.com") // Title contains / equals .titleContains("Login") .titleIs("Home Page")
Common Selenium Exceptions
Exceptions & when they occur
// Element not in DOM NoSuchElementException → Wrong locator / element not loaded yet // Element in DOM but not visible ElementNotVisibleException → Use explicit wait for visibility // Another element is on top ElementClickInterceptedException → Scroll to element or use JS click // Element was found, then DOM changed StaleElementReferenceException → Re-find element before using it // Page took too long to load TimeoutException → Increase wait timeout // WebDriver not found / wrong path WebDriverException → Use WebDriverManager // No alert present NoAlertPresentException → Wait for alert before switching // Window/Frame not available NoSuchWindowException NoSuchFrameException
Window Handling · iFrame · Alert / Popup · JavaScript Executor · Screenshot
Window / Tab Handling
Switch between multiple windows/tabs
// Get current window handle String parent = driver.getWindowHandle(); // Get all window handles Set<String> handles = driver.getWindowHandles(); // Switch to new window for (String h : handles) { if (!h.equals(parent)) { driver.switchTo().window(h); break; } } // Do work in new window... // Switch back to parent driver.switchTo().window(parent); // Open new tab (Selenium 4) driver.switchTo().newWindow( WindowType.TAB); // Open new window (Selenium 4) driver.switchTo().newWindow( WindowType.WINDOW);
iFrame Handling
Switch into and out of iFrames
// Switch by index (0-based) driver.switchTo().frame(0); // Switch by name or ID attribute driver.switchTo().frame("iframeName"); // Switch by WebElement WebElement iframe = driver .findElement(By.id("myFrame")); driver.switchTo().frame(iframe); // Now interact inside frame driver.findElement( By.id("frameInput")).sendKeys("Hi"); // Switch to parent frame driver.switchTo().parentFrame(); // Switch back to main content driver.switchTo().defaultContent(); // Wait for frame then switch wait.until(ExpectedConditions .frameToBeAvailableAndSwitchToIt( By.id("myFrame")));
Alert / Popup Handling
Handle JS alert, confirm, prompt
// Wait for alert wait.until(ExpectedConditions .alertIsPresent()); // Switch to alert Alert alert = driver.switchTo().alert(); // Get alert text String msg = alert.getText(); // Accept (OK button) alert.accept(); // Dismiss (Cancel button) alert.dismiss(); // Send text to prompt dialog alert.sendKeys("Next Gen QA"); alert.accept(); // Complete flow example try { Alert a = driver.switchTo().alert(); String txt = a.getText(); System.out.println("Alert: "+txt); a.accept(); } catch(NoAlertPresentException e) { System.out.println("No alert found"); }
JavascriptExecutor & Screenshot
Execute JS & take screenshots
// Cast driver to JavascriptExecutor JavascriptExecutor js = (JavascriptExecutor) driver; // Click via JS (bypass intercepted) js.executeScript( "arguments[0].click();", element); // Scroll to element js.executeScript( "arguments[0].scrollIntoView(true);", element); // Scroll to bottom of page js.executeScript( "window.scrollTo(0, document.body.scrollHeight)"); // Get element attribute via JS String val = (String) js.executeScript( "return arguments[0].value;", element); // Highlight element (for debugging) js.executeScript( "arguments[0].style.border='3px solid red'", element); // Take screenshot File src = ((TakesScreenshot)driver) .getScreenshotAs(OutputType.FILE); FileUtils.copyFile(src, new File("screenshot.png")); // Screenshot as Base64 String b64 = ((TakesScreenshot)driver) .getScreenshotAs(OutputType.BASE64);
Cookies · TestNG Annotations · Page Object Model (POM) · Assertions
Cookie Handling
Get / Add / Delete cookies
// Get all cookies Set<Cookie> cookies = driver.manage().getCookies(); // Get specific cookie by name Cookie c = driver.manage() .getCookieNamed("sessionId"); String val = c.getValue(); // Add a cookie Cookie newCookie = new Cookie("token", "abc123"); driver.manage().addCookie(newCookie); // Delete specific cookie driver.manage() .deleteCookieNamed("sessionId"); // Delete all cookies driver.manage().deleteAllCookies(); // Print all cookie names & values for (Cookie ck : cookies) { System.out.println( ck.getName() + " = " + ck.getValue()); }
TestNG Annotations
All TestNG annotations in order
@BeforeSuite // Runs once before all tests @AfterSuite // Runs once after all tests @BeforeTest // Before each <test> tag in XML @AfterTest // After each <test> tag @BeforeClass // Before first method in class @AfterClass // After last method in class @BeforeMethod // Before EACH @Test method @AfterMethod // After EACH @Test method @Test // Marks a test method // @Test parameters @Test(priority = 1) @Test(enabled = false) @Test(groups = {"smoke"}) @Test(dependsOnMethods = {"login"}) @Test(dataProvider = "testData") @Test(expectedExceptions = ArithmeticException.class) @Test(timeOut = 3000) // ms @Test(invocationCount = 3)
TestNG DataProvider & Assertions
Data-driven testing & verify results
// DataProvider method @DataProvider(name = "loginData") public Object[][] getData() { return new Object[][] { {"admin", "pass123"}, {"user1", "abc456"} }; } @Test(dataProvider = "loginData") public void loginTest( String u, String p) { // use u and p here } // TestNG Assertions Assert.assertEquals(actual, expected); Assert.assertTrue(condition); Assert.assertFalse(condition); Assert.assertNull(object); Assert.assertNotNull(object); Assert.assertNotEquals(a, b); // Soft Assert — don't stop on fail SoftAssert sa = new SoftAssert(); sa.assertEquals(actual, expected); sa.assertTrue(flag); sa.assertAll(); // throw if any failed
Page Object Model (POM)
Standard POM structure with PageFactory
// LoginPage.java — Page class public class LoginPage { WebDriver driver; // @FindBy locators @FindBy(id = "username") WebElement userField; @FindBy(id = "password") WebElement passField; @FindBy(id = "loginBtn") WebElement loginBtn; // Constructor — init elements public LoginPage(WebDriver d) { this.driver = d; PageFactory.initElements(d, this); } // Page actions as methods public void login( String u, String p) { userField.sendKeys(u); passField.sendKeys(p); loginBtn.click(); } } // LoginTest.java — Test class public class LoginTest { @Test public void testLogin() { LoginPage lp = new LoginPage(driver); lp.login("admin", "pass123"); } }
testng.xml · File Upload · Scroll · Table Handling · Selenium Grid · Extent Reports
testng.xml Configuration
Suite XML file structure
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> <suite name="NextGenQA Suite" parallel="methods" thread-count="3"> <test name="Smoke Tests"> <groups> <run> <include name="smoke"/> </run> </groups> <classes> <class name="tests.LoginTest"/> <class name="tests.SearchTest"/> </classes> </test> <test name="Regression"> <parameter name="browser" value="chrome"/> <classes> <class name="tests.AllTests"/> </classes> </test> </suite>
File Upload & Scroll
Upload file using sendKeys
// File upload via input[type='file'] WebElement upload = driver .findElement( By.cssSelector("input[type='file']")); upload.sendKeys( "C:\\files\\resume.pdf");
Scroll operations
// Scroll by pixels (x, y) js.executeScript( "window.scrollBy(0, 500)"); // Scroll to element js.executeScript( "arguments[0].scrollIntoView()", element); // Scroll to top of page js.executeScript( "window.scrollTo(0, 0)"); // Scroll to bottom of page js.executeScript( "window.scrollTo(0," + "document.body.scrollHeight)"); // Scroll using Actions (Selenium 4) new Actions(driver) .scrollToElement(element) .perform();
Table Handling
Read rows, columns & cells from HTML table
// Get all rows from table body List<WebElement> rows = driver .findElements( By.xpath("//table/tbody/tr")); // Get row count int rowCount = rows.size(); System.out.println("Rows: "+rowCount); // Get column count from row 1 List<WebElement> cols = driver .findElements( By.xpath("//table/tbody/tr[1]/td")); int colCount = cols.size(); // Read all cell data for (int r=1; r<=rowCount; r++) { for (int c=1; c<=colCount; c++) { String cell = driver .findElement(By.xpath( "//table/tbody/tr["+r +"]/td["+c+"]")) .getText(); System.out.print(cell+"\t"); } System.out.println(); } // Find row by cell value WebElement row = driver .findElement(By.xpath( "//td[text()='Khan Sir']/.."));
Base Test Class Template
Reusable base class for all tests
public class BaseTest { protected WebDriver driver; protected WebDriverWait wait; @BeforeMethod public void setUp() { WebDriverManager .chromedriver().setup(); driver = new ChromeDriver(); driver.manage().window() .maximize(); driver.manage().timeouts() .implicitlyWait( Duration.ofSeconds(10)); wait = new WebDriverWait(driver, Duration.ofSeconds(15)); driver.get( "https://your-app-url.com"); } @AfterMethod public void tearDown() { if (driver != null) { driver.quit(); } } // Utility: Take screenshot on fail @AfterMethod public void captureOnFail( ITestResult result) { if (result.getStatus() == ITestResult.FAILURE) { File src = ((TakesScreenshot)driver) .getScreenshotAs( OutputType.FILE); FileUtils.copyFile(src, new File("screenshots/" + result.getName() + ".png")); } } }