You are on page 1of 15

Selenium Syntax Reference

1. System.setProperty("webdriver.ie.driver", "D:\\temp\\iedriverserver.exe");

// Create driver object for ie driver

WebDriver driver = new InternetExplorerDriver();

System.setProperty("webdriver.chrome.driver", "D:\\temp\\chromedriver.exe");

WebDriver driver = new ChromeDriver();

2. How to open URL

driver.get("http://www.google.com"); // Open and wait till the whole page load

driver.navigate.to("http://www.google.com"); // Open but not wait till the whole page loads.

3. driver.navigate().back();

driver.navigate().forward();

driver.navigate().refresh();

driver.manage().window().maximize();

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


for(Cookie cookie : cookies)
System.out.println(cookie);
driver.manage().deleteAllCookies();

4. driver.getTitle();

driver.getCurrentUrl();

driver.getPageSource();

5. WebElement Locators: There are 8 webelement locators

ID, Name, Class Name, xpath, CSS, linkText, Partial Link Text, tagName.

driver.findElement(By.id("dfsdfad"));

driver.findElement(By.Name("erwerwerw"));

Sreehari, B
Retrieving WebElement Properties:

1. Object Properties

2. Object Methods

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

1. String strText = element.getText();

2. String tagName = element.getTagName();

3. String className = element.getClassName();

4. Dimension dimension = element.getSize(); // width and height

dimension.widhth;

dimension.height;

5. Point point= element.getLocation(); // returns(x,y) position

System.out.println("X Position : "point.x);

System.out.println("Y Position : "point.y);

getAttributes

1. element.getAttribute("value");

2. element.getAttribute("align");

getCSSValue

1. element.getCSSValue("width");

2. element.getCSSValue("background-color");

3. element.getCSSValue("font-famliy");

boolean displayStatus = element.isDisplayed();

boolean selectStatus = element.isSelected();

boolean enableStatus = element.isEnabled ();

Sreehari, B
Operations/Methods On WebElement

element.click();

element.sendKeys("Selenium");

element.sendKeys(Key.Enter); // Click on Enter key of keyboard

element.submit(); // if input type = submit

What is difference between findElement and findElements?

findElements method will return list of all elements matching from the current page

as per given element locator mechanisim.

findElement method will return only one element matching from the current page

as per given element locator mechanisim.

Radio Button and Radio Group

/html/body/div/div/div[1]/p[1]/select

xpath of one Radio button : /html/body/div[1]/div/div[1]/p[2]/input[1]

//input[@value ='Petrol']

//input[@value ='Diesel']

WebElement petrol = driver.findElement(By.xpath("//input[@value ='Petrol']");

// Check already selected

if(!petrol.isSelected())

petrol.click();

Sreehari, B
Radio Group

List <WebElement> fuelType = driver.findElements(By.name("fuel_type");

for(WebElement i : fuelType)

String strActual = i.getAttribute("value");

String strExpected = "Diesel";

if(strActual.equalsIgnoreCase(strExpected)

if(!i.isSelected())

i.click();

Check box:

WebElement airBags = driver.findElement(By.xpath("//input[@value ='airbags']");

// Check already selected

if(!airbags.isSelected())

airbags.click();

Dropdowns and Lists

1. List <WebElement> class

2. Select Class // HTML <select> element as id

Sreehari, B
1. Using List

List<WebElement> list = driver.findElements(By.xpath("abc"));

//Find the size

int l = list.size();

// Code to find the expected list box item in a collection of list items

String strExpected = "Audi";

for(int i=0; i<l; i++)

String strActual = list.get(i).getText();

if(strActual.equals(strExpected)

boolean status = true;

if(status)

System.out.println("Element found");

else

System.out.println("Element not found");

2. Using Select

Select dropdown = new Select(driver.findElement(By.name("make"));

int n = dropdown.getOptions().size();

// To find the default selected option

String strFirst = dropdown.getFirstSelectedOption().getText();

Sreehari, B
//How to select dropdowns

dropdown.selectByVisibleText("Audi");

dropdown.selectByValue("audi");

dropdown.selectByIndex(2);

// Multiselect

Boolean isMultiple = dropdown.isMultiple();

int m = dropdown.getAllSelectedOptions().size();

// deselect

dropdown.deselectByVisibleText("Audi");

dropdown.deselectByValue("audi");

dropdown.deselectByIndex(2);

dropdown.deselectAll();

a) How to take screen shot?

import java.io.File;

import org.openqa.selenium.OutputType;

import org.openqa.selenuim.TakesScreenshot;

import org.apache.commons.io.FileUtils;

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

FileUtils.copyFile(scr, new File("D:\\temp\\screenshot.jpg"));

b) To include date and time while taking screen shot

import java.io.File;

import java.util.Calendar;

import java.text.SimpleDateFormat;

Sreehari, B
// Get current date and time in a string

Calendar currentDate = Calendar.getInstance();

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mmm-dd HH-MM-SS");

String dateTime = formatter.format(currentDate.getTime());

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

FileUtils.copyFile(scr, new File("D:\\temp\\screenshot" + dateTime + ".jpg"));

-------

Alert

import org.openqa.selenium.Alert;

// To generate alert

driver.findElement(By.xpath("dsjflkjdflk")).click();

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

String msg = A.getText();

//To click on Ok or Accept

A.accept();

/ /To click on Cancel or No

A.dismiss();

// To type text in alert box

A.sendKeys("This is selenium");

Handling pop up windows

String myWindowHandle = driver.getWindowHandle();

driver.switchTo().window(myWindowHandle);

//To close the window

1. driver.findElement(By.id("locator of close window")).click();

2. driver.close();

Sreehari, B
NoSuchWindowException: The driver.switchTo().window()

method throws the "NoSuchWindowException" exception when it fails to identify the desired
window.

// Get handles of all the open windows

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

if(! allWindows.isEmpty)

for(String winId : allWindows)

try{

if( (driver.switchTo().window(winId).getTitle()).equals("Visit Us") )

System.out.println("Visit us window found");

driver.close();

break;

catch(NoSuchWindowExpection e)

e.printStackTrace();

// move back to parent window

driver.switchTo().window(parentWindowId);

----------------------------- **************** --------------------------

Sreehari, B
How to verify if an element is displayed in the current web page?

Boolean isEelementPresent = driver.findElements(By.xpath("abc")).size() !=0;

It will return true if the element is present in the page, else it return false.

Frames:

HTML frames allow developers to present documents in multiple views, which may be
independent

windows or subwindows.

A page with frames is created by using <frameset> tag. or the <iframe> tag.

All the frame tags are nested in a <frameset> tag.

driver.swithTo().frame(driver.findElement(By.classname("demo-name"));

driver.swithTo().defaultContent();

Frames can be identified by an ID or Name or Index.

driver.switchTo().frame(0);

driver.switchTo().frame(1);

driver.switchTo().frame(2);

For empty frames, we need to activate the frame.

Ex: WebElement editbale = driver.switchTo().activateElement();

editable.sendKeys("Welcome");

driver.swithTo().defaultContent();

// Identifying and handling frames by their content

// Get all frames on the page with the frame tag.

Sreehari, B
List<WebElement> frames = driver.findElements(By.tagName("frame"));

for(WebElement framei : frames)

driver.switchTo().frame(framei)

if(driver.getPageSource().contains("This is demo ID"))

assertTrue("Middle Frame Found", true);

break;

else

driver.switchTo().defaultContent();

WebTable Element:

WebTable Rows Columns

Name No Sal emailid } Row 0

Kalyan 123 50000 zya@gmail.com } Row 1

Kumar 124 60000 zhya@gmail.com } Row 2

Madhu 125 70000 azya@gmail.com } Row 3

Ravi 126 90000 czya@gmail.com } Row 4

tr and td = table row and table definition

Sreehari, B
EX: /table/tbody/tr[0]/td[0] = 1

/table/tbody/tr[0]/td[1] = 2

/table/tbody/tr[0]/td[2] = 3

/table/tbody/tr[1]/td[0]

/table/tbody/tr[1]/td[1]

/table/tbody/tr[1]/td[2]

/table/tbody/tr[2]/td[0]

/table/tbody/tr[2]/td[1]

/table/tbody/tr[2]/td[2]

td0 td1 td2


tr0 1 2 3

tr1 4 5 6

tr2 7 8 9

// Find Table with name

WebElement tableEmp = driver.findElement(By.name("employee"));

// Find all rows in the tableEmp

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

// Find all columns in the first row

List<WebElement> cols0 = rows.get(0).findElements(By.tagName("td"));

List<WebElement> cols1 = rows.get(1).findElements(By.tagName("td"));

List<WebElement> cols2 = rows.get(2).findElements(By.tagName("td"));

Sreehari, B
// To find the size

int rowCount = rows.size();

// Find a cell value position in a table

for(int i=0; i<rows.size(); i++) {

List<WebElement> cols = rows.get(i).findElements(By.tagName("td"));

for(j =0; j<cols.size(); j++) {

String cellValue = cols.get(j).getText();

String ExpValue = "22:13"

if(cellValue.equalsIgnoreCase(ExpValue)) {

System.out.println("Value found at location" + i + j);

break; } }

// To find number of columns

int colCount0 = cols0.size();

String cellValue02 = cols0.get(2).getText();

-----------------------------------------------------------------

Synchronization : AUT = Application Under Test

Automation Tool = Selenium

1. implicit wait : Just wait for some time. Will wait for maximum amount of time.

2. explicit wait : Wait for some time and check for object each 500 milliseconds.

3. fluent wait : Define your own polling and wait time.

Sreehari, B
Thread.sleep(3000); // Java statement

1. implicit wait: DM TIW

driver.manage().timeouts().implicitlyWait(10, TimeUNIT.SECONDS);

// driver will wait for an element to appear in DOM for 10 seconds after an initial try

2. Explicit Wait:

The selenium Webdriver provides WebDriverWait and ExpectedConditions classes

to implement an Explicit wait.

Ex1 : WebDriverWait wait = new WebDriverWait(driver, 10);

wait.until(ExpectedConditions.titleContains("selenium");

The WebDriverWait object will call the ExpectedConditions class object every

500 milliseconds until it returns successfully.

// In the above code 10 stands for 10 seconds. Default polling time is 500 msecs.

Ex2 : WebDriverWait wait = new WebDriverWait(driver, 10);

wait.until(ExpectedConditions.elementToBeClicable(By.xpath("abc"));

Predefined Condition Selenium Method

1. An element is visible and enabled elementToBeClicable(By locator)

2. An element is selected elementToBeSelected(WebElement element)

3. Presence of an Element presenceOfElemenLocated(By locator)

4. Title titleContains(java.lang.String title)

5. Specific text present in an element textToBePresentInElement(By


locator,java.lang.String text)

6. Element Value textToBePresentInElementValue(By locator,


java.lang.String text)

Sreehari, B
3. Fluent Wait:

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)

.withTimeout(10, TimeUnit.SECONDS)

.pollingEvery(2, TimeUnit.SECONDS)

.ignoring(NoSuchElementException.class);

--------------

Text Box with AutoOptions:

<ul class="ui-autocomplete ui-front ui-corner-all" id="ui-id-1">

<li data-id="123" data-no="1" select-id="results[0]" class="selected">Chennai</li>

<li data-id="581" data-no="2" select-id="results[1]">Chengannur</li>

<li data-id="91436" data-no="3" select-id="results[2]">Chennur</li>

<li data-id="81543" data-no="4" select-id="results[3]">Chenchupet</li>

<li data-id="199965" data-no="5" select-id="results[4]">Chenani</li>

<li data-id="200654" data-no="6" select-id="results[5]">Chengalpet</li>

<li data-id="75614" data-no="7" select-id="results[6]">Chennimalai</li>

<li data-id="86944" data-no="8" select-id="results[7]">Chengam</li>

<li data-id="68804" data-no="9" select-id="results[8]">Chengalpattu</li>

<li data-id="198349" data-no="10" select-id="results[9]">Chennekothapalli</li>

</ul>

WebElement from = driver.findElement(By.id("src"));

from.clear();

from.sendKeys("Che");

Sreehari, B
WebElement autoOption = driver.findElement(By.id('ui-id-1'));

wait.until(ExpectedConditions.visibityOf("autoOption"));

String expFrom = "Chennai";

List<WebElement> fromAutoOptions = autoOption.findElements(By.tagName("li"));

for(WebElement fromAutoOption : fromAutoOptions)

String actualFrom = fromAutoOption.getText();

if(expFrom.equalsIgnoreCase(actualFrom))

fromAutoOption.click();

break;

}}

-----

//To find all the links in the webPage

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


System.out.println("Number of links =" +allLinks.size());
for(WebElement link :allLinks)
System.out.println(link.getText());
//Google search options
driver.get("http://www.google.com");
driver.findElement(By.name("q")).sendKeys("Canada");
Thread.sleep(5000);
List <WebElement> allLinks = driver.findElements(By.xpath("//div[@role='option']"));
System.out.println("Number of All Links ="+ allLinks.size());
for(WebElement i: allLinks)
System.out.println(i.getText());

Sreehari, B

You might also like