0% found this document useful (0 votes)
9 views

Selenium With Java Cheat Sheet

This cheat sheet provides essential Selenium commands for Java, including methods for locating elements, working with frames, windows, files, alerts, and performing actions like clicking and dragging. It also covers driver initialization for different browsers and basic Selenium Grid setup. Additionally, it includes annotations for TestNG and JUnit testing frameworks to manage test execution flow.

Uploaded by

ishivamkunal
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)
9 views

Selenium With Java Cheat Sheet

This cheat sheet provides essential Selenium commands for Java, including methods for locating elements, working with frames, windows, files, alerts, and performing actions like clicking and dragging. It also covers driver initialization for different browsers and basic Selenium Grid setup. Additionally, it includes annotations for TestNG and JUnit testing frameworks to manage test execution flow.

Uploaded by

ishivamkunal
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/ 2

Selenium with Java Cheat Sheet

Locating Elements Working with Frames


By ID: driver.findElement(By.id (<element
Switch to a frame by name or ID:
ID>))
driver.switchTo().frame("buttonframe");
By Name: driver.findElement(By.name(<element
name>))
Switch to a frame by index:
driver.findElement(By.className
By Class Name: (<element class>))
driver.switchTo().frame(1);

driver.findElement(By.tagName
Switch to a frame using a WebElement:
By Tag Name: (<html tag name>)) WebElement iframe =
driver.findElement(By.cssSelector("#modal>iframe"));
driver.findElement(By.cssSelector(" driver.switchTo().frame(iframe);
By CSS Selector: Tag#Value of id attribute"))
Switch back to the main content:
driver.findElement(By.xpath
By XPath: (“//input[@type='submit']”)) driver.switchTo().defaultContent();

driver.findElement(By.linkText
By Link Text: (<link text>))

driver.findElement(By.partialLinkTe
Working with Files
By Partial Link Text: xt (<link text>))
Upload a file:
driver.findElement(By.id("file-

Working with Windows


upload")).sendKeys(“path/to/your/file.txt”);
driver.findElement(By.id("file-submit")).submit();

Read data from a text file - Using


Get the current window handle: BufferedReader:
String mainWindowHandle = driver.getWindowHandle();
FileInputStream inputStream = new FileInputStream(“MyFile.txt”);
InputStreamReader reader = new InputStreamReader(inputStream, “UTF-
Get all window handles: 16”);
int character;
import java.util.Set; while ((character = reader.read()) != -1) {
Set<String> allWindowHandles = driver.getWindowHandles(); System.out.print((char) character);
}
Switch to a specific window: reader.close();

String windowHandle = driver.getWindowHandle(); Using FileReader:


driver.switchTo().window(windowHandle);
FileReader reader = new FileReader(“MyFile.txt”);
Switch to newly created window: int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
driver.switchTo().newWindow(WindowType.TAB); }
driver.switchTo().newWindow(WindowType.WINDOW); reader.close();

Close the current window: Read data from a CSV file:


driver.close(); mport au.com.bytecode.opencsv.CSVReader;
String path = “C:\\Users\\Myuser\\Desktop\\csvtest.csv”;
Set window position: Reader reader = new FileReader(path);
CSVReader csvreader = new CSVReader(reader);
driver.manage().window().setPosition(new Point(0, 0)); List<String[]> data = csvreader.readAll();
for(String[] d : data){
for(String c : d ){
Maximize window: System.out.println(c);
}
driver.manage().window().maximize(); }

Minimize window: Read data from an Excel file:


driver.manage().window().minimize(); import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
Fullscreen window: import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
driver.manage().window().fullscreen(); File file = new File(“E:\\TestData\\TestData.xls”);
FileInputStream inputStream = new FileInputStream(file);
Take a Screenshot: HSSFWorkbook wb=new HSSFWorkbook(inputStream);
HSSFSheet sheet=wb.getSheet(“STUDENT_DATA”);
import org.apache.commons.io.FileUtils; HSSFRow row2=sheet.getRow(1);
File scrFile = HSSFCell cell=row2.getCell(5);
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); String address= cell.getStringCellValue();
FileUtils.copyFile(scrFile, new File("./image.png"));

Driver Initialization
Chrome WebDriver driver = new ChromeDriver();

Firefox WebDriver driver = new FirefoxDriver();

Edge WebDriver driver = new EdgeDriver();

Safari WebDriver driver = new SafariDriver();


Selenium Grid Working with Alerts
Start the hub Switch to an alert:
java -jar selenium-server-standalone-x.y.z.jar -role hub Alert alert = driver.switchTo().alert();

Start a node Enter text in an alert:


java -jar selenium-server-standalone-x.y.z.jar -role node -hub alert.sendKeys("Selenium");
http://localhost:4444/grid/register
Retrieve alert text:
Server
String text = alert.getText();
http://localhost:4444/ui/index.html

Note: Replace "x.y.z" with the version number of your Selenium Server

Selenium Operations
Standalone JAR file.

Selenium Grid Launch a Webpage:


driver.get("<URL>") or driver.navigate().to("<URL>")
Start the hub
Click a button:
java -jar selenium-server-standalone-x.y.z.jar -role hub
WebElement searchButton = driver.findElement(By.name("btnK"));
searchButton.click();
Start a node
java -jar selenium-server-standalone-x.y.z.jar -role node -hub Print the page title:
Server String title = driver.getTitle();
System.out.println(title);
http://localhost:4444/ui/index.html
Accept an alert pop-up:
driver.switchTo( ).alert( ).accept();
Selenium Navigators
Implicit wait:
Navigate to a URL driver.get("<URL>") or
driver.navigate().to("<URL>")
import java.util.concurrent.TimeUnit;
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

Refresh the page driver.navigate().refresh() Explicit wait:


import java.util.concurrent.TimeUnit;

Navigate forward WebElement firstResult = new WebDriverWait(driver,


Duration.ofSeconds(10))
driver.navigate().forward()
in browser history .until(ExpectedConditions.elementToBeClickable(By.xpath("//a/h3")));

Navigate back in Sleep:


browser history driver.navigate().back() Thread.sleep(<Time in MilliSeconds>);

Clear the input field text:


Mouse Actions WebElement searchInput = driver.findElement(By.name("q"));
searchInput.sendKeys("selenium");
searchInput.clear();

Click: Disable a field (set the ‘disabled’ attribute):


var actions = new Actions(driver); ((IJavaScriptExecutor)driver).ExecuteScript(“document.querySelector(‘
actions.Click(element).Perform(); <element_css_selector>’).setAttribute(‘disabled’, ”);”);

Double click: Enable a field (remove the ‘disabled’ attribute):


actions.DoubleClick(element).Perform(); ((IJavaScriptExecutor)driver).ExecuteScript("document.querySelector('
<element_css_selector>').removeAttribute('disabled');");
Right click:
actions.ContextClick(element).Perform();

Drag and drop: TestNG


actions.DragAndDrop(sourceElement, targetElement).Perform();
@BeforeSuite Will run before the execution of all the
test methods in the suite
Move to element: Will execute before the execution of all
@BeforeTest the test methods of available classes
belonging to that folder
actions.MoveToElement(element).Perform();
@BeforeClass Will execute before the first method of
the current class is invoked

@BeforeMethod Will execute before each test method runs


JUnit This is the main part of our automation
script where we write the business logic
@Test we want to automate
@Test Represents the method or class as a test
block, also accepts parameters. Will execute after the execution of each
@AfterMethod test method
The method with this annotation gets
@Before executed before all the other tests. Will execute after the execution of all
The method with this annotation gets
@AfterClass the test methods of the current class

@BeforeClass executed once before class. Will execute after the execution of all
the test methods of available classes
Will execute before each test method runs @AfterTest belonging to that folder
@After The method with this annotation gets Will execute after the execution of all
executed after all the other tests are @AfterSuite the test methods in the suite
executed.
@AfterClass The method with this annotation gets
executed once after class.
@Ignore
Used to disable the tests from execution,
@Disabled but the corresponding reports of the tests
are still generated.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy