[go: up one dir, main page]

0% found this document useful (0 votes)
25 views21 pages

Selenium doc pdf

Selenium is an open-source framework for automating web browser interactions, widely used for testing web applications across various browsers and platforms. It includes components like WebDriver, IDE, and Grid, supporting multiple programming languages. The document provides a comprehensive guide on using Selenium with Java, covering setup, operations, waits, advanced interactions, and handling web elements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views21 pages

Selenium doc pdf

Selenium is an open-source framework for automating web browser interactions, widely used for testing web applications across various browsers and platforms. It includes components like WebDriver, IDE, and Grid, supporting multiple programming languages. The document provides a comprehensive guide on using Selenium with Java, covering setup, operations, waits, advanced interactions, and handling web elements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Selenium is an open-source framework used for automating web browser interactions.

It
is widely used for testing web applications to ensure they work as expected across
different browsers and platforms. Key features include:

Cross-Browser Compatibility: Works with browsers like Chrome, Firefox, Edge,


and Safari.
Programming Language Support: Supports multiple languages such as Java, Python,
C#, Ruby, and JavaScript.
Components:
Selenium WebDriver: For automating browser actions.
Selenium IDE: A record-and-playback tool for simple test creation.
Selenium Grid: For running tests on multiple machines and browsers
simultaneously.

It helps in creating robust and scalable test automation for web applications.

Performing operations in Selenium with Java involves interacting with web elements on
a web page using Selenium WebDriver. Here's a quick guide on common operations:

1. Set Up Selenium
Before performing operations, ensure you have the following:

Java installed
A Selenium WebDriver dependency in your project (e.g., in a Maven pom.xml
file):

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

2. Launch a Browser

WebDriver driver = new ChromeDriver();


driver.get("https://example.com"); // Navigate to a URL
driver.manage().window().maximize(); // Maximize browser window

3. Locating Elements
Use locators to find web elements:

// By ID
WebElement elementById = driver.findElement(By.id("elementId"));

// By Name
WebElement elementByName = driver.findElement(By.name("elementName"));

// By XPath
WebElement elementByXPath = driver.findElement(By.xpath("//tag[@attribute='value']"));
// By CSS Selector
WebElement elementByCSS =
driver.findElement(By.cssSelector("tag[attribute='value']"));

// By Class Name
WebElement elementByClass = driver.findElement(By.className("className"));

// By Link Text
WebElement elementByLinkText = driver.findElement(By.linkText("Link Text"));

4. Perform Operations

a. Input Text

WebElement inputField = driver.findElement(By.id("inputId"));


inputField.sendKeys("Text to enter");

b. Click

WebElement button = driver.findElement(By.id("buttonId"));


button.click();

c. Clear Input Field

inputField.clear();

d. Get Text

String elementText = driver.findElement(By.id("elementId")).getText();


System.out.println("Text: " + elementText);

e. Get Attribute Value

String attributeValue =
driver.findElement(By.id("elementId")).getAttribute("attributeName");
System.out.println("Attribute Value: " + attributeValue);

f. Select from Dropdown

import org.openqa.selenium.support.ui.Select;

WebElement dropdown = driver.findElement(By.id("dropdownId"));


Select select = new Select(dropdown);
select.selectByVisibleText("Option Text"); // Select by visible text
select.selectByValue("optionValue"); // Select by value
select.selectByIndex(1); // Select by index

g. Handle Alerts

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


alert.accept(); // Accept the alert
alert.dismiss(); // Dismiss the alert

h. Handle Checkboxes/Radios

WebElement checkbox = driver.findElement(By.id("checkboxId"));


checkbox.click(); // Select checkbox
System.out.println("Selected: " + checkbox.isSelected());

i. Switch Between Windows

String mainWindow = driver.getWindowHandle();


Set<String> allWindows = driver.getWindowHandles();
for (String window : allWindows) {
driver.switchTo().window(window);
}
// Switch back to the main window
driver.switchTo().window(mainWindow);

j. Handle Frames

driver.switchTo().frame("frameName"); // Switch to frame by name or ID


driver.switchTo().defaultContent(); // Switch back to the main content

k. Scroll

JavascriptExecutor js = (JavascriptExecutor) driver;


js.executeScript("window.scrollBy(0,500)"); // Scroll down by 500 pixels

5. Validate Conditions
Use assertions or WebDriver methods to verify conditions:

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


if (element.isDisplayed()) {
System.out.println("Element is visible");
}

6. Close the Browser

driver.close(); // Close current browser tab


driver.quit(); // Close all browser windows and end WebDriver session

This outline covers basic operations, but Selenium also supports advanced interactions
like drag-and-drop, mouse hover, and file uploads. Let me know if you need examples of
these!

The Actions class in Selenium is used to handle advanced user interactions like mouse
movements, keyboard actions, drag-and-drop, and more. It provides methods to automate
complex interactions that aren't directly possible with basic WebElement methods.
Steps to Use the Actions Class
1. Import the Actions class:

import org.openqa.selenium.interactions.Actions;

2. Create an instance of the Actions class:

Actions actions = new Actions(driver);

3. Perform the desired action using Actions methods.


4. Use the build() and perform() methods to execute the action:
.perform() : Executes the actions immediately.
.build().perform() : Combines multiple actions into a single operation
and then executes.

Common Methods of Actions Class

1. Mouse Hover

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


actions.moveToElement(element).perform();

2. Right-Click (Context Click)

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


actions.contextClick(element).perform();

3. Double-Click

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


actions.doubleClick(element).perform();

4. Drag-and-Drop

WebElement source = driver.findElement(By.id("sourceElement"));


WebElement target = driver.findElement(By.id("targetElement"));
actions.dragAndDrop(source, target).perform();

5. Click and Hold

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


actions.clickAndHold(element).perform();
actions.release().perform(); // Release the hold

6. Drag-and-Drop with Offset

WebElement source = driver.findElement(By.id("sourceElement"));


actions.clickAndHold(source).moveByOffset(100, 50).release().perform();

7. Send Keys
actions.sendKeys(Keys.ARROW_DOWN).perform(); // Simulate pressing the Down Arrow key

8. Key Down and Key Up

actions.keyDown(Keys.SHIFT).sendKeys("text").keyUp(Keys.SHIFT).perform();
// Types "TEXT" because Shift is held down

9. Move by Offset

actions.moveByOffset(50, 100).click().perform();
// Moves the mouse to the specified offset and clicks

10. Perform a Combination of Actions


You can chain multiple actions together:

actions.moveToElement(element)
.click()
.sendKeys("Some Text")
.build()
.perform();

Example: Drag-and-Drop Example

WebDriver driver = new ChromeDriver();


driver.get("https://example.com/drag-and-drop");

WebElement source = driver.findElement(By.id("draggable"));


WebElement target = driver.findElement(By.id("droppable"));

Actions actions = new Actions(driver);


actions.dragAndDrop(source, target).perform();

driver.quit();

The Actions class is especially useful for creating seamless interactions in


applications with dynamic or complex UI elements like sliders, menus, or drag-and-drop
interfaces. Let me know if you'd like examples for any specific use case!

The JavascriptExecutor interface in Selenium allows executing JavaScript directly


within the browser. This is particularly useful for actions not directly supported by
Selenium WebDriver. Below are examples of using JavascriptExecutor for opening a new
tab and scrolling to view an element.

1. Opening a New Tab


You can use window.open() with JavascriptExecutor to open a new browser tab.

Example Code
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class OpenNewTabExample {


public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");

JavascriptExecutor js = (JavascriptExecutor) driver;


js.executeScript("window.open('https://google.com', '_blank');");

// Optionally, switch to the new tab


for (String tab : driver.getWindowHandles()) {
driver.switchTo().window(tab);
}

System.out.println("Opened a new tab!");


driver.quit();
}
}

2. Scroll to View an Element


Use the scrollIntoView() method in JavaScript to scroll a specific element into view.

Example Code

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;

public class ScrollToViewExample {


public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");

// Locate the element you want to scroll to


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

// Scroll to the element


JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView(true);", element);

System.out.println("Scrolled to the element!");


driver.quit();
}
}
Key Points
1. Opening New Tabs:

Use window.open() with _blank to create a new tab.


Switching to the new tab requires handling driver.getWindowHandles() .

2. Scrolling:

scrollIntoView(true) ensures the element is brought into the visible


area of the browser viewport.
Use true for aligning the element at the top of the viewport and false
to align it at the bottom.

1. Waits in Selenium

Implicit Wait:
It sets a default waiting time for all elements.

WebDriver driver = new ChromeDriver();


driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10)); // Wait up to 10
seconds for elements
driver.get("https://example.com");

WebElement element = driver.findElement(By.id("exampleId")); // Selenium will wait if


the element isn't found immediately

Explicit Wait with Expected Conditions:

Waits for a specific condition to be true before proceeding.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;

WebDriver driver = new ChromeDriver();


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

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


timeout
WebElement element =
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("exampleId"))); // Wait
until the element is visible
element.click();

Fluent Wait:

Allows more control over polling intervals.

import org.openqa.selenium.support.ui.FluentWait;
import java.time.Duration;
FluentWait<WebDriver> wait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(20))
.pollingEvery(Duration.ofSeconds(2))
.ignoring(NoSuchElementException.class);

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


element.click();

2. Expected Conditions
Some common ExpectedConditions:

visibilityOfElementLocated(By locator) : Waits for an element to become visible.


elementToBeClickable(By locator) : Waits until an element is clickable.
presenceOfElementLocated(By locator) : Waits until the element is present in the
DOM.
titleContains(String title) : Waits for the title to contain specific text.

Example:

WebElement button =
wait.until(ExpectedConditions.elementToBeClickable(By.id("submitButton")));
button.click();

3. XPaths

Common XPath Syntax

1. Absolute XPath: Starts from the root node.

WebElement element =
driver.findElement(By.xpath("/html/body/div[1]/div/button"));

2. Relative XPath: Starts from anywhere in the DOM.

WebElement element = driver.findElement(By.xpath("//button[@id='exampleId']"));

Examples
Select by attribute:

WebElement element = driver.findElement(By.xpath("//input[@type='text']"));

Contains text:

WebElement element =
driver.findElement(By.xpath("//h1[contains(text(),'Welcome')]"));

Using OR/AND:

WebElement element = driver.findElement(By.xpath("//input[@id='email' or


@name='username']"));

Parent/Child relationship:
WebElement element =
driver.findElement(By.xpath("//div[@class='container']/button"));

4. Robot Class to Copy File Path and Upload File


The Robot Class can simulate keyboard and mouse actions for tasks like uploading
files.

Steps
1. Use setClipboardData to copy the file path to the clipboard.
2. Use Robot to paste and press Enter.

Example

import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;

public class FileUploadExample {


public static void main(String[] args) throws AWTException {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com/upload");

// Click the upload button to open the file upload dialog


WebElement uploadButton = driver.findElement(By.id("uploadButton"));
uploadButton.click();

// Copy file path to clipboard


String filePath = "C:\\path\\to\\your\\file.txt";
StringSelection selection = new StringSelection(filePath);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, null);

// Use Robot class to paste and press Enter


Robot robot = new Robot();
robot.delay(1000);

// Press Ctrl + V
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);

// Press Enter
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);

System.out.println("File uploaded successfully!");


}
}
Summary
Waits: Use ExpectedConditions or FluentWait for dynamic waits.
Xpaths: Leverage relative paths for flexibility.
Robot Class: Useful for simulating keyboard actions like file uploads where
standard WebDriver methods fail.

1. findElement vs findElements

Feature findElement findElements

Finds the first matching


Purpose Finds all matching elements.
element.

Return
WebElement List<WebElement>
Type

Throws NoSuchElementException if no Returns an empty list if no


Exception element is found. elements are found.

Example

Examples:

// findElement - Finds only the first matching element


WebElement element = driver.findElement(By.xpath("//div[@class='item']"));
System.out.println(element.getText());

// findElements - Returns a list of all matching elements


List<WebElement> elements = driver.findElements(By.xpath("//div[@class='item']"));
for (WebElement el : elements) {
System.out.println(el.getText());
}

2. ChromeOptions / FirefoxOptions / EdgeOptions


These classes allow you to customize browser settings, such as adding arguments,
disabling notifications, and setting up headless mode.

ChromeOptions Example:

import org.openqa.selenium.chrome.ChromeOptions;

ChromeOptions options = new ChromeOptions();


options.addArguments("--start-maximized"); // Maximize the browser
options.addArguments("--disable-notifications"); // Disable notifications
options.addArguments("--headless"); // Headless mode
WebDriver driver = new ChromeDriver(options);

FirefoxOptions Example:

import org.openqa.selenium.firefox.FirefoxOptions;
FirefoxOptions options = new FirefoxOptions();
options.addArguments("--private"); // Open in private mode
options.addArguments("--headless"); // Headless mode
WebDriver driver = new FirefoxDriver(options);

EdgeOptions Example:

import org.openqa.selenium.edge.EdgeOptions;

EdgeOptions options = new EdgeOptions();


options.addArguments("--inprivate"); // Open in incognito mode
WebDriver driver = new EdgeDriver(options);

3. Handling Web Tables

Steps:
1. Identify the table.
2. Loop through rows and columns to retrieve data.

Example:

WebElement table = driver.findElement(By.id("tableId"));

// Get all rows


List<WebElement> rows = table.findElements(By.tagName("tr"));

for (WebElement row : rows) {


// Get all columns in the row
List<WebElement> cols = row.findElements(By.tagName("td"));
for (WebElement col : cols) {
System.out.println(col.getText());
}
}

4. Checking for Broken Links

Steps:
1. Retrieve all anchor tags ( <a> ).
2. Extract the href attribute.
3. Send an HTTP request to check the response status.

Example:

import java.net.HttpURLConnection;
import java.net.URL;

List<WebElement> links = driver.findElements(By.tagName("a"));

for (WebElement link : links) {


String url = link.getAttribute("href");

try {
HttpURLConnection connection = (HttpURLConnection) new
URL(url).openConnection();
connection.setRequestMethod("HEAD");
connection.connect();
int responseCode = connection.getResponseCode();

if (responseCode >= 400) {


System.out.println(url + " is a broken link.");
} else {
System.out.println(url + " is valid.");
}
} catch (Exception e) {
System.out.println(url + " is invalid.");
}
}

5. Desired Capabilities, Selenium Grid, and RemoteWebDriver

Desired Capabilities:

Defines configurations for browsers, such as platform, browser version, etc.

DesiredCapabilities caps = new DesiredCapabilities();


caps.setBrowserName("chrome");
caps.setPlatform(Platform.WINDOWS);

Selenium Grid:

Selenium Grid allows executing tests on multiple machines remotely.

RemoteWebDriver Example:

import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

URL gridUrl = new URL("http://localhost:4444/wd/hub");


DesiredCapabilities caps = new DesiredCapabilities();
caps.setBrowserName("chrome");

WebDriver driver = new RemoteWebDriver(gridUrl, caps);


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

6. Integration with BrowserStack/SauceLabs/LambdaTest

BrowserStack Example:

DesiredCapabilities caps = new DesiredCapabilities();


caps.setCapability("browser", "Chrome");
caps.setCapability("browser_version", "latest");
caps.setCapability("os", "Windows");
caps.setCapability("os_version", "10");

caps.setCapability("name", "Sample Test");


caps.setCapability("browserstack.user", "YOUR_USERNAME");
caps.setCapability("browserstack.key", "YOUR_ACCESS_KEY");

WebDriver driver = new RemoteWebDriver(new URL("https://hub.browserstack.com/wd/hub"),


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

LambdaTest Example:

DesiredCapabilities caps = new DesiredCapabilities();


caps.setCapability("browserName", "Chrome");
caps.setCapability("browserVersion", "latest");
caps.setCapability("platformName", "Windows 10");

caps.setCapability("user", "YOUR_USERNAME");
caps.setCapability("accessKey", "YOUR_ACCESS_KEY");

WebDriver driver = new RemoteWebDriver(new URL("https://hub.lambdatest.com/wd/hub"),


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

SauceLabs Example:

DesiredCapabilities caps = new DesiredCapabilities();


caps.setCapability("browserName", "chrome");
caps.setCapability("platform", "Windows 10");
caps.setCapability("version", "latest");

String sauceURL = "https://USERNAME:ACCESS_KEY@ondemand.saucelabs.com:443/wd/hub";


WebDriver driver = new RemoteWebDriver(new URL(sauceURL), caps);
driver.get("https://example.com");

To perform a click using JavascriptExecutor , you can use the click() method in
JavaScript. Here's how you can do it in Selenium Java:

Code Example

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;

public class ClickWithJavascript {


public static void main(String[] args) {
// Set up WebDriver
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");

// Find the element you want to click


WebElement button = driver.findElement(By.id("exampleButtonId"));
// Use JavascriptExecutor to click on the element
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", button);

System.out.println("Button clicked using JavascriptExecutor!");


driver.quit();
}
}

Explanation
1. JavascriptExecutor :
The executeScript method runs JavaScript in the context of the current
page.

2. arguments[0].click() :
arguments[0] refers to the first argument passed (in this case, the
button WebElement).
.click() is the JavaScript method to trigger a click event.

When to Use JavascriptExecutor for Clicks


If the element is not interactable due to overlapping or hidden issues.
If a regular click action fails due to complex front-end logic or animation.

In Selenium, you can perform double click and context click (right click) using the
Actions class. Below are examples for both actions:

1. Double Click
The doubleClick() method in the Actions class is used to perform a double-click on
an element.

Example Code

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class DoubleClickExample {


public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");

// Locate the element to double-click


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

// Create an Actions instance


Actions actions = new Actions(driver);
// Perform double-click action
actions.doubleClick(element).perform();

System.out.println("Double click performed!");


driver.quit();
}
}

2. Context Click (Right Click)


The contextClick() method in the Actions class is used to perform a right-click on
an element.

Example Code

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class ContextClickExample {


public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");

// Locate the element to right-click


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

// Create an Actions instance


Actions actions = new Actions(driver);

// Perform right-click action


actions.contextClick(element).perform();

System.out.println("Right click performed!");


driver.quit();
}
}

Key Points
1. Actions Class:

Used for complex interactions like double-click, right-click, drag-and-


drop, etc.
Call perform() to execute the action.

2. Use Cases:

Double click: For triggering actions like editing text or opening


detailed views.
Right click: For opening context menus or performing additional options.
Selenium exceptions occur when a problem arises during the execution of a test script.
Understanding common exceptions and how to handle them can make your test scripts more
robust and reliable. Below is an overview of Selenium exceptions and their handling:

1. Common Selenium Exceptions

Exception Description How to Handle

Use dynamic waits like


Thrown when an element is WebDriverWait or FluentWait
NoSuchElementException
not found in the DOM. to wait for the
element.

Thrown when a command


Check your wait time
exceeds the time
and conditions. Ensure
TimeoutException specified for execution
the element is
(e.g., waiting for an
present/visible.
element).

Occurs when the Re-locate the element


referenced element is no before interacting with
StaleElementReferenceException
longer attached to the it. Use retry logic or
DOM. refresh the DOM.

Thrown when an element is Check the visibility of


found but cannot be the element and ensure
ElementNotInteractableException
interacted with (e.g., it's enabled before
hidden or disabled). interacting.

Validate window handles


Occurs when trying to
before switching and
NoSuchWindowException switch to a window that
handle window changes
no longer exists.
dynamically.

Verify the frame's


Thrown when trying to
presence using
NoSuchFrameException switch to a frame that
driver.findElements()
does not exist.
before switching.

Thrown when the provided


Verify and correct the
locator is invalid (e.g.,
InvalidSelectorException locator syntax before
syntax error in XPath or
executing the script.
CSS selector).

A generic exception for Ensure the WebDriver is


issues with the WebDriver properly set up and
WebDriverException
(e.g., driver not started running. Restart the
or disconnected). driver if needed.

Occurs when a click Use JavaScriptExecutor


action is intercepted by to click the element or
ElementClickInterceptedException
another element (e.g., ensure the element is
overlapping elements). not obscured.

MoveTargetOutOfBoundsException Thrown when trying to Scroll to the element


move to an element using JavascriptExecutor
outside the viewable before interacting with
area. it.

2. Handling Selenium Exceptions


You can use try-catch blocks or implement dynamic waits to handle exceptions
gracefully.

Example: Handling NoSuchElementException

try {
WebElement element = driver.findElement(By.id("nonExistentId"));
element.click();
} catch (NoSuchElementException e) {
System.out.println("Element not found: " + e.getMessage());
}

Example: Handling Multiple Exceptions

try {
WebElement element = driver.findElement(By.id("exampleId"));
element.click();
} catch (NoSuchElementException e) {
System.out.println("Element not found: " + e.getMessage());
} catch (ElementNotInteractableException e) {
System.out.println("Element not interactable: " + e.getMessage());
} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
}

3. Using Dynamic Waits to Avoid Exceptions


Dynamic waits can reduce the chances of encountering exceptions like
NoSuchElementException and TimeoutException .

Using WebDriverWait

import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;

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


try {
WebElement element =
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("exampleId")));
element.click();
} catch (TimeoutException e) {
System.out.println("Element was not found within the timeout period: " +
e.getMessage());
}
4. Common Best Practices for Exception Handling
1. Validate Locators:

Ensure locators (e.g., XPath, CSS Selectors) are correct before using
them.

2. Use Dynamic Waits:

Avoid using Thread.sleep() and prefer WebDriverWait or FluentWait .

3. Retry Logic:

Implement retry logic for transient exceptions like


StaleElementReferenceException .

4. Catch Specific Exceptions:

Handle specific exceptions rather than catching Exception broadly, for


better debugging.

5. Fail Gracefully:

Log the error and continue with the next test step if appropriate.

5. Framework-Level Exception Handling


In advanced frameworks, you can implement custom exception handling for all Selenium
commands. For example:

Use a try-catch wrapper around WebDriver actions.


Create utility methods to perform actions like safeClick() or
safeFindElement() .

Example of safeClick Method

public void safeClick(By locator) {


try {
WebElement element = driver.findElement(locator);
element.click();
} catch (ElementClickInterceptedException e) {
System.out.println("Click intercepted. Retrying...");
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", driver.findElement(locator));
} catch (Exception e) {
System.out.println("Unexpected error while clicking: " + e.getMessage());
}
}

1. Scroll Up or Down in Selenium


You can scroll using JavascriptExecutor .

Scroll Down
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,1000)"); // Scroll down by 1000 pixels

Scroll Up

js.executeScript("window.scrollBy(0,-1000)"); // Scroll up by 1000 pixels

Scroll to View a Specific Element

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


js.executeScript("arguments[0].scrollIntoView(true);", element);

2. Handling Cookies

Add a Cookie

Cookie cookie = new Cookie("cookieName", "cookieValue");


driver.manage().addCookie(cookie);

Get All Cookies

Set<Cookie> cookies = driver.manage().getCookies();


for (Cookie c : cookies) {
System.out.println(c.getName() + ": " + c.getValue());
}

Delete a Cookie

driver.manage().deleteCookieNamed("cookieName");

Delete All Cookies

driver.manage().deleteAllCookies();

3. Chrome Options - Various Arguments


ChromeOptions allows you to customize the browser’s behavior.

Common Arguments

ChromeOptions options = new ChromeOptions();


options.addArguments("--start-maximized"); // Open in maximized mode
options.addArguments("--incognito"); // Open in incognito mode
options.addArguments("--disable-notifications"); // Disable pop-up notifications
options.addArguments("--headless"); // Headless mode
options.addArguments("--disable-extensions"); // Disable extensions
options.addArguments("--disable-popup-blocking"); // Disable popup blocking
options.addArguments("--no-sandbox"); // Disable sandboxing (for CI/CD)
WebDriver driver = new ChromeDriver(options);
4. Taking a Screenshot

Capture Entire Page

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import java.io.File;
import org.apache.commons.io.FileUtils;

File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);


FileUtils.copyFile(screenshot, new File("screenshot.png"));

Capture Element Screenshot

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


File screenshot = element.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("element_screenshot.png"));

5. Handling Iframes

Switch to Iframe

driver.switchTo().frame("frameName"); // By name or ID
driver.switchTo().frame(0); // By index
WebElement iframeElement = driver.findElement(By.id("iframeId"));
driver.switchTo().frame(iframeElement); // By WebElement

Switch Back to Default Content

driver.switchTo().defaultContent(); // Switches to the main page

Switch to Parent Frame

driver.switchTo().parentFrame(); // Switches to the parent frame

6. pageLoadStrategy , Refresh Page, quit vs close

pageLoadStrategy

Used to control when Selenium considers the page to be fully loaded.

ChromeOptions options = new ChromeOptions();


options.setPageLoadStrategy(PageLoadStrategy.EAGER); // Options: NORMAL, EAGER, NONE
WebDriver driver = new ChromeDriver(options);

Refresh Page

driver.navigate().refresh(); // Refresh the current page

quit vs close
driver.quit() : Closes all browser windows opened by WebDriver and ends the
session.
driver.close() : Closes the current browser window but keeps the session
running.

7. Code to Switch to Desired Window

Switch to a Window Using Title

String mainWindow = driver.getWindowHandle();


Set<String> allWindows = driver.getWindowHandles();

for (String window : allWindows) {


driver.switchTo().window(window);
if (driver.getTitle().equals("Desired Title")) {
break;
}
}

Switch to a Window Using URL

for (String window : driver.getWindowHandles()) {


driver.switchTo().window(window);
if (driver.getCurrentUrl().equals("https://desired-url.com")) {
break;
}
}

Return to Main Window

driver.switchTo().window(mainWindow);

You might also like