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: [Link]([Link]("idValue")); //*[@type='submit'] → any tag with type submit
name: [Link]([Link]("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: [Link]([Link] ("classValue"));
//input[ends-with(@id, 'P7')] → selects id that ends with p7
tagName: [Link]([Link] ("html tagName")); //h2[@id='page-ent' or @class='nav-flex'] → one or the other statement
cssSelector: [Link]([Link]("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: [Link]([Link]("//input[@type='submit']")); //*[contains(text(), 'Welcome to')] → selects only text that contains
linkText: [Link]([Link] ("Sale")); → Use index when there are multiple matches
partialLinkText: [Link]([Link] ("link text")); CSS Selector:
.classValue → [Link](".form-control")
#idValue → [Link]("#ageCont")
Selenium Operations Wait Operations
Launch a Webpage: Selenium Dynamic Wait
[Link]("[Link] Implicit wait – global wait:
OR [Link]().to("[Link] [Link]().timeouts().implicitlyWait([Link](10));
Click a button: Explicit wait – local wait:
WebElement searchBtn = [Link]([Link]("btnK")).click(); 1. Create WebDriverWait object
OR [Link](); WebDriverWait wait = new WebDriverWait(driver,[Link](10));
Accept an alert pop-up: [Link]( ).alert( ).accept(); 2. Use the object to add expected conditions
Print the page title: WebElement classABC = [Link](ExpectedConditions
String title = [Link](); [Link](title); .visibilityOfElementLocated([Link](".classlocator")));
Clear the input field text: → better than implicit wait when element is not visible / clickable / displayed
WebElement searchInput = [Link]([Link]("q")); FluentWait – local wait. Is like Explicit wait with more options:
[Link]("selenium"); [Link](); Wait<WebDriver> fluentWait = new FluentWait<WebDriver>(driver)
Disable a field (set the ‘disabled’ attribute): .withTimeout([Link](30))
JavascriptExecutor javascript = (JavascriptExecutor) driver; .pollingEvery([Link](5))//will check every 5 sec
String toDisable = "[Link]('fname')[0] .ignoring([Link]); //ignores exception
.setAttribute('disabled', ");"; Same as Explicit Wait:
[Link](toDisable); WebElement classABC = [Link](ExpectedConditions
Enable a field (remove the ‘disabled’ attribute): .visibilityOfElementLocated([Link](".classlocator")));
JavascriptExecutor javascript = (JavascriptExecutor) driver; ScriptTimeout & PageLoad Timeout:
String toEnable = "[Link]('fname')[0] [Link]().timeouts().scriptTimeout([Link](2));
.setAttribute(enabled, ");"; [Link]().timeouts().pageLoadTimeout([Link](10));
[Link](toEnable); Java hard wait ->
Sleep: [Link](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 [Link]("URL")
[Link]().alert().accept();
OR [Link]().to("URL");
Dissmiss an alert: Same as clicking Cancel of an alert.
[Link]().alert().dismiss(); Refresh the page [Link]().refresh();
Enter text in an alert box: Navigate forward in browser [Link]().forward();
[Link]().alert().sendKeys("Selenium")
Retrieve alert text: To get the alert message of the alert. Navigate back in browser [Link]().back();
[Link]().alert().getText();
Java Faker Drop Down List
Copy Faker dependency into [Link] file Step 1: Locate the dropdown element:
1. Create a Faker object WebElement month=[Link]([Link]("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([Link]("firstname")) [Link](0);
.sendKeys([Link]().firstName()); [Link]("1");
OR [Link]("Jan");
String fName = [Link]().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 = [Link]();
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 = [Link]();
[Link]().frame(0) will switch the first iframe 2. Get all window handles:
2. id/name: Set<String> allWindowHandles = [Link]();
[Link]().frame("id or name of the iframe"); 3. Switch to a specific window:
3. web element (locators): for (String eachHandle : allWindowHandles){
WebElement middleFrame = if (){
[Link]([Link]("//frame[@name='left']")); [Link]().window(eachHandle);
[Link]().frame(middleFrame); }
→ Switching back to parent / default frame: }
To parent frame goes only 1 level up: OR
◦ [Link]().parentFrame(); String windowHandle = [Link]();
To get back to the main fraim: [Link]().window(windowHandle);
◦ [Link]().defaultContent();
Returns the total number of iframe on a page Switch to newly created window:
◦ [Link]([Link]("iframe")); [Link]().newWindow([Link]);
[Link]().newWindow([Link]);
Actions
Step 1: Create the action object: Close the current window:
Actions actions=new Actions(driver); [Link]();
Step 2: Locate the WebElement you want to work on: Set window position:
WebElement element = [Link]([Link]("ID")); [Link]().window().setPosition(new Point(0, 0));
Step 3: Perform the action on the WebElement Maximize window:
Right click: [Link](element).perform(); [Link]().window().maximize();
Hover over: [Link](element).perform(); Minimize window:
actions .sendKeys(Keys.ARROW_DOWN) [Link]().window().minimize();
.sendKeys(Keys.ARROW_UP) Fullscreen window:
.sendKeys(Keys.PAGE_DOWN) [Link]().window().fullscreen();
.sendKeys(Keys.PAGE_UP)
.build() //OPTIONAL : recommended with method chains Take a Screenshot:
.perform(); //MANDATORY import [Link];
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([Link]);
get IllegalArgumentException. [Link](scrFile, new File("./[Link]"));
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
[Link]([Link]("upload")).sendKeys("path/to/the/[Link]"); [Link]("[Link]"); =>gives the path of the current folder
[Link]([Link]("file-submit")).submit();
[Link]("[Link]"); =>gives you the user folder
Read data from an Excel file: [Link]([Link]("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/[Link]";
1. Creating a reference
OR File file = new File(“resources/[Link]”);
JavascriptExecutor js = (JavascriptExecutor) driver;
2. Open the file
2. Calling the method
FileInputStream fileInputStream = new FileInputStream(path);
3. Open the workbook using fileinputstream [Link](Script, Arguments);
Workbook workbook = [Link](fileInputStream); [Link](return something);
4. Open the first worksheet Example: Clicking on a button
Sheet sheet1 = [Link]("Sheet1"); WebElement button =[Link]([Link]("btnLogin"));
OR [Link](0); //ALTERNATIVE //Perform Click on LOGIN button using JavascriptExecutor
5. Go to first row [Link]("arguments[0].click();", button);
Row row1 = [Link](0); //arguments[0] -> the first argument in executeScript method
6. Go to first cell on that first row and print
Cell cell1 = [Link](0); Selenium Grid
Read data from a text file using BufferedReader: Start the hub:
FileReader reader = new FileReader("[Link]"); java -jar [Link] -role hub
BufferedReader bufferedReader = new BufferedReader(reader); Start a node:
String line; java -jar [Link] -role node -hub
while ((line = [Link]()) != null) Server
{ [Link](line); }
[Link]
[Link]();
Read data from a text file Using InputStream:
FileInputStream inputStream = new FileInputStream("[Link]");
InputStreamReader reader = new InputStreamReader(inputStream,
"UTF-16");
int character;
while ((character = [Link]()) != -1)
{ [Link]((char) character); }
[Link]();
Read data from a text file Using FileReader:
FileReader reader = new FileReader("[Link]");
int character;
while ((character = [Link]()) != -1)
{ [Link]((char) character); }
[Link]();
Read data from a CSV file:
import [Link];
String path = "C:\\Users\\Myuser\\Desktop\\[Link]";
Reader reader = new FileReader(path);
CSVReader csvreader = new CSVReader(reader);
List<String[]> data = [Link]();
for(String[] d : data){
for(String c : d ){
[Link](c); } }