Selenium doc pdf
Selenium doc pdf
It
is widely used for testing web applications to ensure they work as expected across
different browsers and platforms. Key features include:
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
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
b. Click
inputField.clear();
d. Get Text
String attributeValue =
driver.findElement(By.id("elementId")).getAttribute("attributeName");
System.out.println("Attribute Value: " + attributeValue);
import org.openqa.selenium.support.ui.Select;
g. Handle Alerts
h. Handle Checkboxes/Radios
j. Handle Frames
k. Scroll
5. Validate Conditions
Use assertions or WebDriver methods to verify conditions:
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;
1. Mouse Hover
3. Double-Click
4. Drag-and-Drop
7. Send Keys
actions.sendKeys(Keys.ARROW_DOWN).perform(); // Simulate pressing the Down Arrow key
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
actions.moveToElement(element)
.click()
.sendKeys("Some Text")
.build()
.perform();
driver.quit();
Example Code
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
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;
2. Scrolling:
1. Waits in Selenium
Implicit Wait:
It sets a default waiting time for all elements.
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;
Fluent Wait:
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);
2. Expected Conditions
Some common ExpectedConditions:
Example:
WebElement button =
wait.until(ExpectedConditions.elementToBeClickable(By.id("submitButton")));
button.click();
3. XPaths
WebElement element =
driver.findElement(By.xpath("/html/body/div[1]/div/button"));
Examples
Select by attribute:
Contains text:
WebElement element =
driver.findElement(By.xpath("//h1[contains(text(),'Welcome')]"));
Using OR/AND:
Parent/Child relationship:
WebElement element =
driver.findElement(By.xpath("//div[@class='container']/button"));
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;
// 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);
1. findElement vs findElements
Return
WebElement List<WebElement>
Type
Example
Examples:
ChromeOptions Example:
import org.openqa.selenium.chrome.ChromeOptions;
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;
Steps:
1. Identify the table.
2. Loop through rows and columns to retrieve data.
Example:
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;
try {
HttpURLConnection connection = (HttpURLConnection) new
URL(url).openConnection();
connection.setRequestMethod("HEAD");
connection.connect();
int responseCode = connection.getResponseCode();
Desired Capabilities:
Selenium Grid:
RemoteWebDriver Example:
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
BrowserStack Example:
LambdaTest Example:
caps.setCapability("user", "YOUR_USERNAME");
caps.setCapability("accessKey", "YOUR_ACCESS_KEY");
SauceLabs Example:
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;
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.
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;
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;
Key Points
1. Actions Class:
2. Use Cases:
try {
WebElement element = driver.findElement(By.id("nonExistentId"));
element.click();
} catch (NoSuchElementException e) {
System.out.println("Element not found: " + e.getMessage());
}
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());
}
Using WebDriverWait
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
Ensure locators (e.g., XPath, CSS Selectors) are correct before using
them.
3. Retry Logic:
5. Fail Gracefully:
Log the error and continue with the next test step if appropriate.
Scroll Down
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,1000)"); // Scroll down by 1000 pixels
Scroll Up
2. Handling Cookies
Add a Cookie
Delete a Cookie
driver.manage().deleteCookieNamed("cookieName");
driver.manage().deleteAllCookies();
Common Arguments
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import java.io.File;
import org.apache.commons.io.FileUtils;
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
pageLoadStrategy
Refresh 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.
driver.switchTo().window(mainWindow);