📘 Selenium WebDriver Detailed
Cheatsheet (for SDET)
1. Setup & Launching Browsers
Concept:
● Selenium WebDriver is an API that allows controlling browsers programmatically.
● Each browser needs its driver (ChromeDriver, GeckoDriver for Firefox, EdgeDriver,
SafariDriver).
Example (Java):
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class LaunchBrowser {
public static void main(String[] args) {
// Set driver path (not needed in Selenium 4.6+ with Selenium
Manager)
System.setProperty("webdriver.chrome.driver",
"path/to/chromedriver");
WebDriver driver = new ChromeDriver(); // Launch Chrome
driver.get("https://www.google.com"); // Open URL
System.out.println("Page Title: " + driver.getTitle()); //
Print title
driver.quit(); // Close browser
}
}
2. Navigation Commands
Concept:
● Used to move between pages like back, forward, refresh.
Example:
driver.navigate().to("https://www.google.com");
driver.navigate().back();
driver.navigate().forward();
driver.navigate().refresh();
3. Locators (Finding Elements)
Concept:
● Selenium provides 8 locators to find elements.
Locators:
1. id
2. name
3. className
4. tagName
5. linkText
6. partialLinkText
7. cssSelector
8. xpath
Example:
driver.findElement(By.id("username")).sendKeys("testuser");
driver.findElement(By.name("password")).sendKeys("password123");
driver.findElement(By.className("btn-login")).click();
driver.findElement(By.linkText("Forgot Password?")).click();
driver.findElement(By.partialLinkText("Forgot")).click();
driver.findElement(By.cssSelector("input[type='email']")).sendKeys("te
[email protected]");
driver.findElement(By.xpath("//button[text()='Login']")).click();
4. WebElement Methods
Common Actions:
● click() → click element
● sendKeys("text") → enter input
● clear() → clear input box
● getText() → get element text
● getAttribute("value") → get attribute value
● isDisplayed() / isEnabled() / isSelected() → check state
Example:
WebElement email = driver.findElement(By.id("email"));
email.sendKeys("[email protected]");
System.out.println(email.getAttribute("value")); // prints typed text
5. Handling Alerts
Concept:
● Alerts are popups that need to be switched before performing actions.
Example:
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept(); // OK
alert.dismiss(); // Cancel
alert.sendKeys("Some text"); // Prompt
6. Handling Frames
Concept:
● Pages may contain <iframe> tags.
● You need to switch to perform actions.
Example:
driver.switchTo().frame(0); // by index
driver.switchTo().frame("frameName"); // by name/id
driver.switchTo().frame(driver.findElement(By.xpath("//iframe[@id='fra
meId']"))); // by element
driver.switchTo().defaultContent(); // back to main page
7. Handling Multiple Windows
Concept:
● Selenium can switch between multiple tabs/windows using window handles.
Example:
String parent = driver.getWindowHandle();
Set<String> handles = driver.getWindowHandles();
for (String handle : handles) {
if (!handle.equals(parent)) {
driver.switchTo().window(handle);
System.out.println(driver.getTitle());
driver.close();
}
}
driver.switchTo().window(parent);
8. Dropdowns
Concept:
● Use Select class for <select> elements.
Example:
WebElement dropdown = driver.findElement(By.id("country"));
Select select = new Select(dropdown);
select.selectByIndex(1);
select.selectByValue("IND");
select.selectByVisibleText("India");
List<WebElement> options = select.getOptions();
for (WebElement opt : options) {
System.out.println(opt.getText());
}
9. Waits
Concept:
● Synchronization between script & browser.
● Types:
○ Implicit Wait → waits globally
○ Explicit Wait → waits for condition
○ Fluent Wait → advanced wait with polling
Example:
// Implicit Wait
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
// Explicit Wait
WebDriverWait wait = new WebDriverWait(driver,
Duration.ofSeconds(15));
WebElement el =
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("userna
me")));
// Fluent Wait
Wait<WebDriver> fwait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(20))
.pollingEvery(Duration.ofSeconds(2))
.ignoring(NoSuchElementException.class);
11. Handling Frames & iFrames
👉 Websites often embed pages inside frames/iframes.
To interact with elements inside, you must switch context.
Example 1: Switch by index
driver.switchTo().frame(0); // first frame
driver.findElement(By.id("username")).sendKeys("anas");
driver.switchTo().defaultContent(); // back to main page
Example 2: Switch by name or ID
driver.switchTo().frame("frameName");
driver.findElement(By.id("password")).sendKeys("pass123");
driver.switchTo().parentFrame(); // one step back
Example 3: Nested frames
driver.switchTo().frame("outerFrame").switchTo().frame("innerFrame");
driver.findElement(By.id("submit")).click();
✅ Always switch back after work (defaultContent/parentFrame).
12. Handling Multiple Windows / Tabs
👉 Selenium assigns a WindowHandle (unique ID) to each tab.
You must switch context to perform actions.
Example:
String parent = driver.getWindowHandle();
Set<String> allWindows = driver.getWindowHandles();
for (String handle : allWindows) {
if (!handle.equals(parent)) {
driver.switchTo().window(handle);
System.out.println("Child window title: " +
driver.getTitle());
driver.close(); // close child
}
}
driver.switchTo().window(parent); // back to parent
13. Actions Class (Mouse & Keyboard Events)
👉 Used for complex user gestures: hover, drag-drop, right click, etc.
Hover & Click
Actions actions = new Actions(driver);
WebElement menu = driver.findElement(By.id("menu"));
WebElement submenu = driver.findElement(By.id("submenu"));
actions.moveToElement(menu).click(submenu).build().perform();
Drag and Drop
WebElement src = driver.findElement(By.id("draggable"));
WebElement dest = driver.findElement(By.id("droppable"));
actions.dragAndDrop(src, dest).perform();
Keyboard Events
actions.sendKeys(Keys.ENTER).perform();
actions.keyDown(Keys.CONTROL).click(link).keyUp(Keys.CONTROL).perform(
);
14. JavaScriptExecutor
👉 When Selenium fails to interact normally (hidden elements, dynamic
scripts).
JavascriptExecutor js = (JavascriptExecutor) driver;
// Scroll
js.executeScript("window.scrollBy(0,500)");
// Click
WebElement button = driver.findElement(By.id("submit"));
js.executeScript("arguments[0].click();", button);
// Set value
js.executeScript("arguments[0].value='Hello';",
driver.findElement(By.id("name")));
15. Screenshots
Full Page Screenshot
File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("./screenshots/test.png"));
Element Screenshot
WebElement ele = driver.findElement(By.id("logo"));
File src = ele.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("./screenshots/logo.png"));
16. File Upload / Download
Upload (using sendKeys)
driver.findElement(By.id("fileUpload")).sendKeys("C:\\path\\file.txt")
;
AutoIT / Robot (when sendKeys doesn’t work)
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_V);
robot.keyPress(KeyEvent.VK_ENTER);
17. Data-Driven Testing (Excel with Apache
POI)
👉 Read test data from Excel for input values.
Read Data
FileInputStream fis = new FileInputStream("testdata.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheet("Login");
String username = sheet.getRow(1).getCell(0).getStringCellValue();
String password = sheet.getRow(1).getCell(1).getStringCellValue();
driver.findElement(By.id("user")).sendKeys(username);
driver.findElement(By.id("pass")).sendKeys(password);
Write Data
sheet.getRow(1).createCell(2).setCellValue("PASS");
FileOutputStream fos = new FileOutputStream("testdata.xlsx");
wb.write(fos);
18. TestNG Integration
👉 TestNG provides annotations, assertions, and reports.
Example
import org.testng.Assert;
import org.testng.annotations.Test;
public class LoginTest {
@Test
public void testLogin() {
driver.get("https://site.com/login");
driver.findElement(By.id("user")).sendKeys("anas");
driver.findElement(By.id("pass")).sendKeys("pass123");
driver.findElement(By.id("loginBtn")).click();
String title = driver.getTitle();
Assert.assertEquals(title, "Dashboard");
}
}
TestNG Features
● @BeforeSuite, @BeforeClass, @BeforeMethod
● @After* equivalents
● Parallel execution with XML
● dataProvider for DDT
19. Page Object Model (POM) Recap
👉 Separates test logic from element locators.
public class LoginPage {
WebDriver driver;
By username = By.id("user");
By password = By.id("pass");
By loginBtn = By.id("loginBtn");
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public void login(String user, String pass) {
driver.findElement(username).sendKeys(user);
driver.findElement(password).sendKeys(pass);
driver.findElement(loginBtn).click();
}
}
Test:
LoginPage login = new LoginPage(driver);
login.login("anas", "pass123");
20. Page Factory
👉 Reduces boilerplate with @FindBy.
public class LoginPage {
WebDriver driver;
@FindBy(id="user") WebElement username;
@FindBy(id="pass") WebElement password;
@FindBy(id="loginBtn") WebElement loginBtn;
public LoginPage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void login(String user, String pass) {
username.sendKeys(user);
password.sendKeys(pass);
loginBtn.click();
}
}
🚀 Selenium Coding Problems (with
Explanations)
1. Login to a site and validate the title
Logic Approach (step-by-step):
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class LoginTest {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"drivers/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://example.com/login");
// Enter username
WebElement user = driver.findElement(By.id("username"));
user.sendKeys("testuser");
// Enter password
WebElement pass = driver.findElement(By.id("password"));
pass.sendKeys("password123");
// Click login
WebElement loginBtn = driver.findElement(By.id("loginBtn"));
loginBtn.click();
// Validate title manually
String actualTitle = driver.getTitle();
String expectedTitle = "Dashboard";
if(actualTitle.equals(expectedTitle)) {
System.out.println("Test Passed!");
} else {
System.out.println("Test Failed!");
}
driver.quit();
}
}
Optimal Approach (with assertion using TestNG):
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.*;
public class LoginTestNG {
WebDriver driver;
@BeforeMethod
public void setup() {
System.setProperty("webdriver.chrome.driver",
"drivers/chromedriver.exe");
driver = new ChromeDriver();
}
@Test
public void testLogin() {
driver.get("https://example.com/login");
driver.findElement(By.id("username")).sendKeys("testuser");
driver.findElement(By.id("password")).sendKeys("password123");
driver.findElement(By.id("loginBtn")).click();
Assert.assertEquals(driver.getTitle(), "Dashboard", "Login
failed!");
}
@AfterMethod
public void tearDown() {
driver.quit();
}
}
2. Extract all links from a webpage
Logic Approach:
List<WebElement> links = driver.findElements(By.tagName("a"));
for(WebElement link : links) {
System.out.println(link.getAttribute("href"));
}
Optimal Approach (filtering only valid links):
List<WebElement> links = driver.findElements(By.tagName("a"));
links.stream()
.map(e -> e.getAttribute("href"))
.filter(href -> href != null && !href.isEmpty())
.forEach(System.out::println);
3. Handle multiple windows and switch
Logic Approach:
String parent = driver.getWindowHandle();
Set<String> allWindows = driver.getWindowHandles();
for(String win : allWindows) {
if(!win.equals(parent)) {
driver.switchTo().window(win);
System.out.println("Child window title: " +
driver.getTitle());
driver.close(); // closing child
}
}
driver.switchTo().window(parent);
Optimal Approach (Lambda style):
String parent = driver.getWindowHandle();
driver.getWindowHandles().stream()
.filter(win -> !win.equals(parent))
.forEach(win -> {
driver.switchTo().window(win);
System.out.println(driver.getTitle());
driver.close();
});
driver.switchTo().window(parent);
4. Handle frames
Logic Approach:
driver.switchTo().frame(0); // switch by index
driver.findElement(By.id("searchBox")).sendKeys("Selenium");
driver.switchTo().defaultContent(); // back to main
Optimal Approach:
WebElement frameElement =
driver.findElement(By.xpath("//iframe[@id='frame1']"));
driver.switchTo().frame(frameElement);
driver.findElement(By.id("searchBox")).sendKeys("Selenium WebDriver");
driver.switchTo().parentFrame();
5. Capture screenshot
Logic Approach:
File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
File dest = new File("screenshot.png");
Files.copy(src.toPath(), dest.toPath());
Optimal Approach (with timestamp + reusable method):
public static String takeScreenshot(WebDriver driver, String name)
throws IOException {
String timestamp = String.valueOf(System.currentTimeMillis());
File src =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
String path = "screenshots/" + name + "_" + timestamp + ".png";
Files.copy(src.toPath(), Paths.get(path));
return path;
}
6. Wait until element is clickable
Logic Approach:
Thread.sleep(3000); // not optimal
driver.findElement(By.id("submit")).click();
Optimal Approach (Explicit wait):
WebDriverWait wait = new WebDriverWait(driver,
Duration.ofSeconds(10));
WebElement button =
wait.until(ExpectedConditions.elementToBeClickable(By.id("submit")));
button.click();
7. Handle Dropdown Selection
Problem:
Select an option from a dropdown (<select>) with values.
Solution 1 (Manual Iteration - Without Select class):
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.List;
public class DropdownManual {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com/dropdown");
WebElement dropdown = driver.findElement(By.id("country"));
List<WebElement> options =
dropdown.findElements(By.tagName("option"));
for (WebElement option : options) {
if (option.getText().equals("India")) {
option.click();
break;
}
}
}
}
Solution 2 (Optimal - Using Select class):
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
public class DropdownSelect {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com/dropdown");
Select select = new
Select(driver.findElement(By.id("country")));
select.selectByVisibleText("India"); // By text
// select.selectByValue("IN"); // By value
// select.selectByIndex(2); // By index
}
}
8. Drag and Drop using Actions
Solution 1 (Manual - JavaScript execution):
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
public class DragDropJS {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://jqueryui.com/droppable/");
driver.switchTo().frame(0); // inside frame
WebElement src = driver.findElement(By.id("draggable"));
WebElement dest = driver.findElement(By.id("droppable"));
String js = "function createEvent(typeOfEvent) { " +
"var event = document.createEvent('CustomEvent');" +
"event.initCustomEvent(typeOfEvent,true,true,null);" +
"event.dataTransfer = {data:{},
setData:function(key,value){this.data[key]=value;}," +
"getData:function(key){return this.data[key];}};
return event; }" +
"function dispatchEvent(element,event){
if(element.dispatchEvent){element.dispatchEvent(event);} }" +
"var dragStartEvent=createEvent('dragstart');
dispatchEvent(arguments[0],dragStartEvent);" +
"var dropEvent=createEvent('drop');
dispatchEvent(arguments[1],dropEvent);" +
"var dragEndEvent=createEvent('dragend');
dispatchEvent(arguments[0],dragEndEvent);";
((JavascriptExecutor) driver).executeScript(js, src, dest);
}
}
Solution 2 (Optimal - Actions class):
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class DragDropAction {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://jqueryui.com/droppable/");
driver.switchTo().frame(0);
WebElement src = driver.findElement(By.id("draggable"));
WebElement dest = driver.findElement(By.id("droppable"));
Actions act = new Actions(driver);
act.dragAndDrop(src, dest).perform();
}
}
9. Handle Alerts (accept, dismiss, sendKeys)
Solution 1 (Switching manually):
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
public class HandleAlertsManual {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com/alert");
driver.findElement(By.id("alertButton")).click();
Alert alert = driver.switchTo().alert();
System.out.println("Alert Text: " + alert.getText());
alert.accept();
}
}
Solution 2 (Optimal - Covering all alert types):
import org.openqa.selenium.*;
public class HandleAlertsOptimal {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com/alerts");
// Simple Alert
driver.findElement(By.id("alertButton")).click();
driver.switchTo().alert().accept();
// Confirmation Alert
driver.findElement(By.id("confirmButton")).click();
driver.switchTo().alert().dismiss();
// Prompt Alert
driver.findElement(By.id("promptButton")).click();
Alert alert = driver.switchTo().alert();
alert.sendKeys("SDET Candidate");
alert.accept();
}
}
10. Data-Driven Testing (Excel → Selenium)
Solution 1 (Manual - Apache POI read and pass data):
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
public class ExcelReaderManual {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("data.xlsx");
Workbook wb = WorkbookFactory.create(fis);
Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
System.out.print(cell.toString() + "\t");
}
System.out.println();
}
wb.close();
}
}
Solution 2 (Optimal - DataProvider in TestNG):
import org.testng.annotations.*;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
public class ExcelDataTest {
WebDriver driver;
@BeforeMethod
public void setup() {
driver = new ChromeDriver();
driver.get("https://example.com/login");
}
@DataProvider(name="loginData")
public Object[][] getData() throws Exception {
FileInputStream fis = new FileInputStream("data.xlsx");
Workbook wb = WorkbookFactory.create(fis);
Sheet sheet = wb.getSheetAt(0);
int rows = sheet.getLastRowNum();
int cols = sheet.getRow(0).getLastCellNum();
Object[][] data = new Object[rows][cols];
for (int i=1;i<=rows;i++) {
for (int j=0;j<cols;j++) {
data[i-1][j] = sheet.getRow(i).getCell(j).toString();
}
}
wb.close();
return data;
}
@Test(dataProvider="loginData")
public void loginTest(String username, String password) {
driver.findElement(By.id("username")).sendKeys(username);
driver.findElement(By.id("password")).sendKeys(password);
driver.findElement(By.id("loginBtn")).click();
}
@AfterMethod
public void teardown() {
driver.quit();
}
}
11. Capture Screenshot
Solution 1 (Manual - File Copy):
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.File;
import java.nio.file.Files;
public class ScreenshotManual {
public static void main(String[] args) throws Exception {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
File src =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
File dest = new File("screenshot.png");
Files.copy(src.toPath(), dest.toPath());
}
}
Solution 2 (Optimal - Utility Function):
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.apache.commons.io.FileUtils;
import java.io.File;
public class ScreenshotUtility {
public static void takeScreenshot(WebDriver driver, String name)
throws Exception {
File src =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("./screenshots/" + name +
".png"));
}
public static void main(String[] args) throws Exception {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
takeScreenshot(driver, "homepage");
driver.quit();
}
}
12. Wait until element is clickable
Solution 1 (Manual - Loop retry):
import org.openqa.selenium.*;
public class WaitManual {
public static void main(String[] args) throws Exception {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
WebElement btn = null;
for (int i=0; i<10; i++) {
try {
btn = driver.findElement(By.id("submit"));
if (btn.isDisplayed() && btn.isEnabled()) {
btn.click();
break;
}
} catch (Exception e) {}
Thread.sleep(1000);
}
}
}
Solution 2 (Optimal - WebDriverWait):
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.*;
public class WaitOptimal {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement btn =
wait.until(ExpectedConditions.elementToBeClickable(By.id("submit")));
btn.click();
}
}
13. Scroll Page using JavaScript
Solution 1 (Partial scroll):
import org.openqa.selenium.*;
public class ScrollManual {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
((JavascriptExecutor)driver).executeScript("window.scrollBy(0,500)");
}
}
Solution 2 (Scroll into view):
import org.openqa.selenium.*;
public class ScrollOptimal {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
WebElement element = driver.findElement(By.id("footer"));
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoVie
w(true);", element);
}
}
14. Handle Multiple Checkboxes
Solution 1 (Iterate manually):
import org.openqa.selenium.*;
import java.util.List;
public class CheckboxesManual {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com/checkboxes");
List<WebElement> checkboxes =
driver.findElements(By.xpath("//input[@type='checkbox']"));
for (WebElement box : checkboxes) {
if (!box.isSelected()) {
box.click();
}
}
}
}
Solution 2 (Filter specific checkboxes):
import org.openqa.selenium.*;
import java.util.List;
public class CheckboxesOptimal {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com/checkboxes");
List<WebElement> checkboxes =
driver.findElements(By.xpath("//input[@type='checkbox' and
@value='option2']"));
for (WebElement box : checkboxes) {
box.click();
}
}
}
15. Handle Multiple Windows
Solution 1 (Manual iteration):
import org.openqa.selenium.*;
import java.util.Set;
public class WindowsManual {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
String parent = driver.getWindowHandle();
driver.findElement(By.id("newWindowBtn")).click();
Set<String> windows = driver.getWindowHandles();
for (String win : windows) {
if (!win.equals(parent)) {
driver.switchTo().window(win);
System.out.println("Child Title: " +
driver.getTitle());
driver.close();
}
}
driver.switchTo().window(parent);
}
}
Solution 2 (Optimal - Using List & direct access):
import org.openqa.selenium.*;
import java.util.ArrayList;
public class WindowsOptimal {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
driver.findElement(By.id("newWindowBtn")).click();
ArrayList<String> tabs = new
ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1)); // child
System.out.println("Child Title: " + driver.getTitle());
driver.close();
driver.switchTo().window(tabs.get(0)); // back to parent
}
}