COMPLETE REFERENCE · WEBDRIVER · LOCATORS · WAITS · FRAMEWORKS · TESTNG
<!-- 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><dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.9.0</version>
<scope>test</scope>
</dependency>// Auto manages chromedriver
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
options.addArguments("--maximize");
options.addArguments("--incognito");
WebDriver driver = new ChromeDriver(options);WebDriverManager.firefoxdriver().setup();
WebDriver driver = new FirefoxDriver();
WebDriverManager.edgedriver().setup();
WebDriver driver = new EdgeDriver();driver.get("https://example.com");
driver.navigate().to("https://example.com");
driver.navigate().back();
driver.navigate().forward();
driver.navigate().refresh();driver.manage().window().maximize();
driver.manage().window().minimize();
driver.manage().window().fullscreen();
// Set specific size
driver.manage().window()
.setSize(new Dimension(1280, 720));String url = driver.getCurrentUrl();
String title = driver.getTitle();
String src = driver.getPageSource();// Close current active window
driver.close();
// Quit — closes ALL windows
driver.quit();// 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));// 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']"));// 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)")// 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 — 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());
}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?// 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"));// 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();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();
}// 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;
}
}// 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();// 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 projectWait<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")));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"));// 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")// 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// 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);// 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")));// 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");
}// 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);// 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());
}@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)// 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// 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");
}
}<?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 via input[type='file']
WebElement upload = driver
.findElement(
By.cssSelector("input[type='file']"));
upload.sendKeys(
"C:\\files\\resume.pdf");// 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();// 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']/.."));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"));
}
}
}