Selenium – Java Chrome
Driver Initialization
WebDriver driver = new ChromeDriver();
Cheat Sheet
Firefox WebDriver driver = new FirefoxDriver();
Edge WebDriver driver = new EdgeDriver();
Safari WebDriver driver = new SafariDriver();
Locating Elements - By: Dynamic xPath:
id: driver.findElement(By.id("idValue")); //*[@type='submit'] → any tag with type submit
name: driver.findElement(By.name("nameValue")); //h2[contains(@id, 'ageCont')] → selects id that contains ageCont value
(//h2[starts-with(@id, 'u_')])[1] → the first input whose id starts with u_
className: driver.findElement(By.className ("classValue"));
//input[ends-with(@id, 'P7')] → selects id that ends with p7
tagName: driver.findElement(By.tagName ("html tagName")); //h2[@id='page-ent' or @class='nav-flex'] → one or the other statement
cssSelector: driver.findElement(By.cssSelector("input[type= //h2[@id='page-ent' and @class='nav-flex'] → both statements
//*[.= 'Sign in'] → any tag & attribute just give me the text
'submit']"));
//*[(text() = 'Welcome')] → selects only text
xPath: driver.findElement(By.xpath("//input[@type='submit']")); //*[contains(text(), 'Welcome to')] → selects only text that contains
linkText: driver.findElement(By.linkText ("Sale")); → Use index when there are multiple matches
partialLinkText: driver.findElement(By.partialLinkText ("link text")); CSS Selector:
.classValue → By.cssSelector(".form-control")
#idValue → By.cssSelector("#ageCont")
Selenium Operations Wait Operations
Launch a Webpage: Selenium Dynamic Wait
driver.get("https://www.google.com"); Implicit wait – global wait:
OR driver.navigate().to("https://www.google.com"); driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
Click a button: Explicit wait – local wait:
WebElement searchBtn = driver.findElement(By.name("btnK")).click(); 1. Create WebDriverWait object
OR searchButton.click(); WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(10));
Accept an alert pop-up: driver.switchTo( ).alert( ).accept(); 2. Use the object to add expected conditions
Print the page title: WebElement classABC = wait.until(ExpectedConditions
String title = driver.getTitle(); System.out.println(title); .visibilityOfElementLocated(By.cssSelector(".classlocator")));
Clear the input field text: → better than implicit wait when element is not visible / clickable / displayed
WebElement searchInput = driver.findElement(By.name("q")); FluentWait – local wait. Is like Explicit wait with more options:
searchInput.sendKeys("selenium"); searchInput.clear(); Wait<WebDriver> fluentWait = new FluentWait<WebDriver>(driver)
Disable a field (set the ‘disabled’ attribute): .withTimeout(Duration.ofSeconds(30))
JavascriptExecutor javascript = (JavascriptExecutor) driver; .pollingEvery(Duration.ofSeconds(5))//will check every 5 sec
String toDisable = "document.getElementsByName('fname')[0] .ignoring(NoSuchElementException.class); //ignores exception
.setAttribute('disabled', ");"; Same as Explicit Wait:
javascript.executeScript(toDisable); WebElement classABC = wait.until(ExpectedConditions
Enable a field (remove the ‘disabled’ attribute): .visibilityOfElementLocated(By.cssSelector(".classlocator")));
JavascriptExecutor javascript = (JavascriptExecutor) driver; ScriptTimeout & PageLoad Timeout:
String toEnable = "document.getElementsByName('fname')[0] driver.manage().timeouts().scriptTimeout(Duration.ofMinutes(2));
.setAttribute(enabled, ");"; driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(10));
javascript.executeScript(toEnable); Java hard wait ->
Sleep: Thread.sleep(Time in MilliSeconds);
TestNG Annotations JUnit Annotations
@Test the main part of the automation script where @Test Represents the method or class as a test block, also
we write the business logic we want to automate accepts parameters.
@BeforeSuite runs before executing all test methods in the suite @Before The method with this annotation gets executed before all
@BeforeTest executes before executing all test methods of other tests.
available classes belonging to that folder @BeforeClass The method with this annotation gets executed once
@BeforeClass executes before the first method of the current class before class.
is invoked @After The method with this annotation gets executed after all
@BeforeMethod executes before each test method runs other tests are executed.
@AfterSuite executes after executing all test methods in the suite @AfterClass The method with this annotation gets executed once after
@AfterMethod executes after executing each test method class.
@AfterTest executes after executing all test methods of available @Ignore It is used to ignore certain test statements during execution.
classes belonging to that folder @Disabled Used to disable the tests from execution, but the
@AfterClass executes after executing all test methods of the corresponding reports of the tests are still generated.
current class
Alerts Selenium Navigators
Accept an alert: Same as clicking OK of an alert. Navigate to a URL driver.get("URL")
driver.switchTo().alert().accept();
OR driver.navigate().to("URL");
Dissmiss an alert: Same as clicking Cancel of an alert.
driver.switchTo().alert().dismiss(); Refresh the page driver.navigate().refresh();
Enter text in an alert box: Navigate forward in browser driver.navigate().forward();
driver.switchTo().alert().sendKeys("Selenium")
Retrieve alert text: To get the alert message of the alert. Navigate back in browser driver.navigate().back();
driver.switchTo().alert().getText();
Java Faker Drop Down List
Copy Faker dependency into pom.xml file Step 1: Locate the dropdown element:
1. Create a Faker object WebElement month=driver.findElement(By.id("dropdown"));
Faker faker = new Faker(); Step 2: Create Select object and pass the variable to that object:
2. generate fake data Select selectMonth=new Select(month);
driver Step 3: Select from a dropdown using select object with 3 different ways:
.findElement(By.name("firstname")) selectMonth.selectByIndex(0);
.sendKeys(faker.name().firstName()); selectMonth.selectByValue("1");
OR selectMonth.selectByVisibleText("Jan");
String fName = faker.name().firstName(); We can put all dropdown elements in a List<WebElement> using getOptions();
fake data = mock data →fake ssn, fake name, fake address Select selectOptions = new Select(states);
List<WebElement> options = selectOptions.getOptions();
iFrame Working with Windows
A page within a page → we must first switch() to the iframe. 3 ways: 1. Get the current window handle:
1. by index: → index start from 0 String window1Handle = driver.getWindowHandle();
driver.switchTo().frame(0) will switch the first iframe 2. Get all window handles:
2. id/name: Set<String> allWindowHandles = driver.getWindowHandles();
driver.switchTo().frame("id or name of the iframe"); 3. Switch to a specific window:
3. web element (locators): for (String eachHandle : allWindowHandles){
WebElement middleFrame = if (!eachHandle.equals(window1Handle)){
driver.findElement(By.xpath("//frame[@name='left']")); driver.switchTo().window(eachHandle);
driver.switchTo().frame(middleFrame); }
→ Switching back to parent / default frame: }
To parent frame goes only 1 level up: OR
◦ driver.switchTo().parentFrame(); String windowHandle = driver.getWindowHandle();
To get back to the main fraim: driver.switchTo().window(windowHandle);
◦ driver.switchTo().defaultContent();
Returns the total number of iframe on a page Switch to newly created window:
◦ driver.findElements(By.tagName("iframe")); driver.switchTo().newWindow(WindowType.TAB);
driver.switchTo().newWindow(WindowType.WINDOW);
Actions
Step 1: Create the action object: Close the current window:
Actions actions=new Actions(driver); driver.close();
Step 2: Locate the WebElement you want to work on: Set window position:
WebElement element = driver.findElement(By.id("ID")); driver.manage().window().setPosition(new Point(0, 0));
Step 3: Perform the action on the WebElement Maximize window:
Right click: actions.contextClick(element).perform(); driver.manage().window().maximize();
Hover over: actions.moveToElement(element).perform(); Minimize window:
actions .sendKeys(Keys.ARROW_DOWN) driver.manage().window().minimize();
.sendKeys(Keys.ARROW_UP) Fullscreen window:
.sendKeys(Keys.PAGE_DOWN) driver.manage().window().fullscreen();
.sendKeys(Keys.PAGE_UP)
.build() //OPTIONAL : recommended with method chains Take a Screenshot:
.perform(); //MANDATORY import org.apache.commons.io.FileUtils;
keysDown(); → to press and hold a key. Keys mean Shift,Ctrl, Alt keys. File scrFile = ((TakesScreenshot)driver)
keysUp(); → to release a pressed key after keysDown(), otherwise we may .getScreenshotAs(OutputType.FILE);
get IllegalArgumentException. FileUtils.copyFile(scrFile, new File("./image.png"));
sendKeys(element,"text"); → to type into text box / text area
Working with Files Working with Files
Upload a file: We can't test desktop applications with Selenium. But we can use JAVA
driver.findElement(By.id("upload")).sendKeys("path/to/the/file.txt"); System.getProperty("user.dir"); =>gives the path of the current folder
driver.findElement(By.id("file-submit")).submit();
System.getProperty("user.home"); =>gives you the user folder
Read data from an Excel file: Files.exists(Paths.get("path of the file"));
<Apache dependancy>
=>Checks if a file path exists on your computer or not
→ workbook > worksheet > row > cell
→ Index starts with 0 → e.g. row 1 cell 1 has the index of row 0 cell 0
1. Store file path in a string Javascript Executor
String path = "resources/Capitals.xlsx";
1. Creating a reference
OR File file = new File(“resources/Capitals.xlsx”);
JavascriptExecutor js = (JavascriptExecutor) driver;
2. Open the file
2. Calling the method
FileInputStream fileInputStream = new FileInputStream(path);
3. Open the workbook using fileinputstream js.exectueScript(Script, Arguments);
Workbook workbook = WorkbookFactory.create(fileInputStream); js.executeScript(return something);
4. Open the first worksheet Example: Clicking on a button
Sheet sheet1 = workbook.getSheet("Sheet1"); WebElement button =driver.findElement(By.name("btnLogin"));
OR workbook.getSheetAt(0); //ALTERNATIVE //Perform Click on LOGIN button using JavascriptExecutor
5. Go to first row js.executeScript("arguments[0].click();", button);
Row row1 = sheet1.getRow(0); //arguments[0] -> the first argument in executeScript method
6. Go to first cell on that first row and print
Cell cell1 = row1.getCell(0); Selenium Grid
Read data from a text file using BufferedReader: Start the hub:
FileReader reader = new FileReader("MyFile.txt"); java -jar selenium-server-standalone-x.y.z.jar -role hub
BufferedReader bufferedReader = new BufferedReader(reader); Start a node:
String line; java -jar selenium-server-standalone-x.y.z.jar -role node -hub
while ((line = bufferedReader.readLine()) != null) Server
{ System.out.println(line); }
http://localhost:4444/ui/index.html
reader.close();
Read data from a text file Using InputStream:
FileInputStream inputStream = new FileInputStream("MyFile.txt");
InputStreamReader reader = new InputStreamReader(inputStream,
"UTF-16");
int character;
while ((character = reader.read()) != -1)
{ System.out.print((char) character); }
reader.close();
Read data from a text file Using FileReader:
FileReader reader = new FileReader("MyFile.txt");
int character;
while ((character = reader.read()) != -1)
{ System.out.print((char) character); }
reader.close();
Read data from a CSV file:
import au.com.bytecode.opencsv.CSVReader;
String path = "C:\\Users\\Myuser\\Desktop\\csvtest.csv";
Reader reader = new FileReader(path);
CSVReader csvreader = new CSVReader(reader);
List<String[]> data = csvreader.readAll();
for(String[] d : data){
for(String c : d ){
System.out.println(c); } }