Anda di halaman 1dari 40

Introduction:

Selenium is an open source automation testing tool.It is used exclusively for web based
applications.You can work on multiple operating systems using selenium.

1.SeleniumHistory
Selenium came into existence in 2004 when GUY named Jason Huggins was testing an
internal application at ThoughtWorks.
Selenium is a set of different software tools each with a different approach to supporting
test automation.
1.1 Selenium Components:
Selenium IDE
Selenium Remote Control
Selenium WebDriver
Selenium Grid
Lets have a look on each of these components:
Selenium IDE
Selenium IDE is a complete integrated development environment (IDE) for Selenium
tests. It is implemented as a Firefox extension, and allows recording, editing, and
debugging tests. It was previously known as Selenium Recorder.
Scripts are recorded in Selenese, a special test scripting language for Selenium.
Selenese provides commands for performing actions in a browser (click a link, select an
option), and for retrieving data from the resulting pages.
It is not only just play back tool, It can records user actions as they are performed and
then exports them as reusable script in one of many programming languages that can
be later executed.

Drawbacks:

As it will come with only Firefox addin.What if you want to test your application which
works only in Internet explorer or some any other browser?
Selenium IDE is not suitable when you want to built a robust frameworks.Selenium IDE
doesnt provide iteration or conditional statements for test scripts.

Selenium Rc(Selenium 1.0)


Selenium RC was first component in the market which control a browser from a
language of your choice. The underlying functionality of Selenium Remote Control is that
it uses Javascript library(Selenium core) that could drive interactions with the page,
allows us to automatically rerun tests against multiple browsers.
Selenium RC Architecture
There is a selenium-RC server which acts as proxy between our Driver code and
Application under Test
The client/driver establishes a connection with the selenium-RC server.
2. Selenium RC server launches a browser (or reuses an old one) with a URL that injects
Selenium-Cores JavaScript into the browser-loaded web page.
3. The client-driver passes a Selenese command to the server.
4. The Server interprets the command and then triggers the corresponding JavaScript
execution to execute that command within the browser.
5. Selenium-Core instructs the browser to act on that first instruction, typically opening
a page of the AUT.
6. The browser receives the open request and asks for the websites content from the
Selenium RC server (set as the HTTP proxy for the browser to use).
7. Selenium RC server communicates with the Web server asking for the page and once
it receives it, it sends the page to the browser masking the origin to look like the page
comes from the same server as Selenium-Core (this allows Selenium-Core to comply
with the Same Origin Policy).
8. The browser receives the web page and renders it in the frame/window reserved for it

Drawbacks.
As it is entirely use JavaScript to talk to browser, it leads to significant weakness. Every
browser impose very strict security rules on the JavaScript being executed to protect the
users from malicious scripts
There is no support for Android and IOS Platform
Server need to be started every time to run a program.

Lot of Limitations when a Application has Rich API with dynamic elements
Native keyboard and mouse events cannot be handled in efficient manner

Webdriver:(Selenium 2.0)
This brand new automation tool provides all sorts of features, including a more cohesive
and object oriented API as well as an answer to the limitations of the old
implementation.It supports the WebDriver API underlying technology,along with the
Selenium underlying technology.
WebDriver is a tool for automating testing web applications. It is popularly known as
Selenium 2.0. WebDriver uses a different underlying framework, while Selenium RC
uses JavaScript Selenium-Core embedded within the browser which has got some
limitations. WebDriver interacts directly with the browser without any intermediary,
unlike Selenium RC that depends on a server. It is used in the following context:

Multi-browser testing including improved functionality for browsers which is not


well-supported by Selenium RC (Selenium 1.0).

Handling multiple frames, multiple browser windows, popups, and alerts.

Complex page navigation.

Advanced user navigation such as drag-and-drop.

AJAX-based UI elements.

Architecture

The architecture of Selenium Webdriver is entirely different from RC.Unlike RC there is


no proxy server betweenAUT and Code.
It makes direct calls to browser native API to get the things executed.Unlike RC it does
not Use any proxy server to talk to browser. WebDriver uses the most appropriate way
to access the browser API. If we look at Firefox, it uses JavaScript to access the API. If
we look at Internet Explorer, it uses C++. That means that it sometimes needs direct
help from browser development team,By this approach we can control browsers in the

best possible way but has the downside that new browsers entering the market will not
be supported straight away like we can with RC.

WebDriver is best explained with a simple architecture diagram as shown below.

Selenium RC Architecture
Selenium RC works in such a way that the client libraries can communicate with the
Selenium RC Server passing each Selenium command for execution. Then the server

passes the Selenium command to the browser using Selenium-Core JavaScript


commands.
The browser executes the Selenium command using its JavaScript interpreter.

Selenium RC comes in two parts.

The Selenium Server launches and kills browsers. In addition to that, it interprets
and executes the Selenese commands. It also acts as an HTTP proxy by
intercepting and verifying HTTP messages passed between the browser and the
application under test.

Client libraries that provide an interface between each one of the programming
languages (Java, C#, Perl, Python and PHP) and the Selenium-RC Server.

Selenium RC Vs WebDriver
Selenium RC

Selenium WebDriver

The architecture of Selenium RC is


complicated, as the server needs to
be up and running before starting a
test.

WebDriver's architecture is simpler


than Selenium RC, as it controls
the browser from the OS level.

Selenium server acts as a


middleman between the browser
and Selenese commands.

WebDriver interacts directly with


the browser and uses the
browser's engine to control it.

Selenium RC script execution is


slower, since it uses a Javascript to
interact with RC.

WebDriver is faster, as it interacts


directly with the browser.

Selenium RC cannot support


headless execution as it needs a
real browser to work with.

WebDriver can support the


headless execution.

It's a simple and small API.

Complex and a bit large API as


compared to RC.

Less object-oriented API.

Purely object oriented API.

Cannot test mobile Applications.

Can test iPhone/Android


applications.

Scripting using WebDriver


Let us understand how to work with WebDriver. For demonstration, we would use
http://www.calculator.net/. We will perform a "Percent Calculator" which is located
under "Math Calculator". We have already downloaded the required WebDriver JAR's.
Refer the chapter "Environmental Setup" for details.

Step 1 : Launch "Eclipse" from the Extracted Eclipse folder.

Step 2 : Select the Workspace by clicking the 'Browse' button.

Step 3 : Now create a 'New Project' from 'File' menu.

Step 4 : Enter the Project Name and Click 'Next'.

Step 5 : Go to Libraries Tab and select all the JAR's that we have downloaded. Add
reference to all the JAR's of Selenium WebDriver Library folder and also selenium-java2.42.2.jar and selenium-java-2.42.2-srcs.jar.

Step 6 : The Package is created as shown below.

Step 7 : Now right-click on the package and select 'New' >> 'Class' to create a 'class'.

Step 8 : Now name the class and make it the main function.

Step 9 : The class outline is shown as below.

Step 10 : Now it is time to code. The following script is easier to understand, as it has
comments embedded in it to explain the steps clearly. Please take a look at the chapter
"Locators" to understand how to capture object properties.

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
public class webdriverdemo {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
//Puts an Implicit wait, Will wait for 10 seconds before throwing exception
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//Launch website
driver.navigate().to("http://www.calculator.net/");
//Maximize the browser
driver.manage().window().maximize();
// Click on Math Calculators
driver.findElement(By.xpath(".//*[@id='menu']/div[3]/a")).click();
// Click on Percent Calculators
driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/a")).click();
// Enter value 10 in the first number of the percent Calculator
driver.findElement(By.id("cpar1")).sendKeys("10");
// Enter value 50 in the second number of the percent Calculator
driver.findElement(By.id("cpar2")).sendKeys("50");
// Click Calculate Button

driver.findElement(By.xpath(".//*[@id='content']/table/tbody/tr[2]/td/input[2]")).click()
;

// Get the Result Text based on its xpath


String result =
driver.findElement(By.xpath(".//*[@id='content']/p[2]/font/b")).getText();

// Print a Log In message to the screen


System.out.println(" The Result is " + result);
//Close the Browser.
driver.close();
}
}
Step 11 : The output of the above script would be printed in Console.

Most Used Commands


The following table lists some of the most frequently used commands in WebDriver
along with their syntax.
Command

Description

driver.get("URL")

To navigate to an
application.

element.sendKeys("inputtext")

Enter some text into an


input box.

element.clear()

Clear the contents from the


input box.

select.deselectAll()

Deselect all OPTIONs from


the first SELECT on the
page.

select.selectByVisibleText("some text")

Select the OPTION with the


input specified by the user.

driver.switchTo().window("windowName")

Move the focus from one


window to another.

driver.switchTo().frame("frameName")

Swing from frame to frame.

driver.switchTo().alert()

Helps in handling alerts.

driver.navigate().to("URL")

Navigate to the URL.

driver.navigate().forward()

To navigate forward.

driver.navigate().back()

To navigate back.

driver.close()

Closes the current browser


associated with the driver.

driver.quit()

Quits the driver and closes


all the associated window of
that driver.

driver.refresh()

Refreshes the current page.

As Webdriver directly talks with browser we can overcome the limitations of JavaScript
security model which we have face with Selenium Core in RC
Selenium-WebDriver supports the following browsers along with the operating systems
these browsersare compatible with.

Google Chrome 12.0.712.0+


Internet Explorer 6, 7, 8, 9 - 32 and 64-bit where applicable
Firefox 3.0, 3.5, 3.6, 4.0, 5.0, 6, 7
Opera 11.5+
HtmlUnit 2.9
Android 2.3+ for phones and tablets (devices & emulators)
iOS 3+ for phones (devices & emulators) and 3.2+ for tablets (devices & emulators)

Languages on which Webdriver Supports:


Java,
Javascript,
Ruby,
PHP,
Python,
Perl
C#
You can use any of the above language to Automate application.There is nothing rule like
as your website is built with C#,so you have to use only C# code in Webdriver to
automate your application.The language you write your code is Application independent.
Why Webdriver??
In addition, Selenium 2 still runs Selenium 1s Selenium RC interface for backwards
compatibility
No server required to start.
No support for Android and Iphone platform in RC
Can Handle rich API
Can handle Mouse movements
It directly talks to browser. unlike RC it does not use any proxy server
It supports all the Latest Versions of Firefox
All future enhancements can be done in Webdriver only.

Selenium Grid
Selenium Grid allows you to run your tests in parallel, that is,different tests can be run
at the same time on different remote machines. s. Also, if you must run your test suite
on multiple environments you can have different remote machines supporting and

running your tests in them at the same time. In each case Selenium Grid greatly
improves the time it takes to run your suite by making use of parallel processing

Platforms Supported by Selenium


Windows
OS X
Linux
Solaris

Following languages are used with selenium.


-

Java
C#
Ruby
Pyton
PHP
Pearl

Selenium Browsers Support:


InternetExplorer
Firefox
Chrome
Safari

Download and Install Java


Step 1 : Navigate to the URL:

http://www.oracle.com/technetwork/java/javase/downloads/index.html
Step 2 : Go to "Downloads" section and select "JDK Download".

Step 3 : Select "Accept License Agreement" radio button.

Step 4 : Select the appropriate installation. In this case, it is 'Windows 7-64' bit. Click
the appropriate link and save the .exe file to your disk.

Step 5 : Run the downloaded exe file to launch the Installer wizard. Click 'Next' to
continue.

Step 6 : Select the features and click 'Next'.

Step 7 : The installer is extracted and its progress is shown in the wizard.

Step 8 : The user can choose the install location and click 'Next'.

Step 9 : The installer installs the JDK and new files are copied across.

Step 10 : The Installer installs successfully and displays the same to the user.

Step 11 : To verify if the installation was successful, go to the command prompt and
just type 'java' as a command. The output of the command is shown below. If the Java
installation is unsuccessful or if it had NOT been installed, it would throw an "unknown
command" error.

Download and Configure Eclipse


Step 1 : Navigate to the URL: http://www.eclipse.org/downloads/ and download the
appropriate file based on your OS architecture.

Step 2 : Click the 'Download' button.

Step 3 : The download would be in a Zipped format. Unzip the contents.

Step 4 : Locate Eclipse.exe and double click on the file.

Step 5 : To configure the workspace, select the location where the development has to
take place.

Step 6 : The Eclipse window opens as shown below.

Configure FireBug and FirePath


To work with Selenium RC or WebDriver, we need to locate elements based on their
XPath or ID or name, etc. In order to locate an element, we need tools/plugins.
Step 1 : Navigate to the URL : https://addons.mozilla.org/en-US/firefox/addon/firebug/
and download plugin.

Step 2 : The add-on installer is shown to the user and it is installed upon clicking the
'Install' button.

Step 3 : After installing, we can launch the plugin by navigating to "Web Developer"
>> "Firebug".

Step 4 : FirePath, a plugin that works within Firebug, helps users to grab the 'XPath' of
an element. Install FirePath by navigating to "https://addons.mozilla.org/enUS/firefox/addon/firepath/"

Step 5 : The add-on installer is shown to the user and it is installed upon clicking the
'Install' button.

Step 6 : Now launch "Firebug" by navigating to "Tools" >> "Webdeveloper" >>


"Firebug".

Interface:

A Java interface defines a set of methods but does not implement them. A class that
implements the interface agrees to implement all of the methods defined in the
interface.

All Known Implementing Classes:


AndroidDriver, AndroidWebDriver, ChromeDriver, EventFiringWebDriver, FirefoxDri
ver, HtmlUnitDriver, InternetExplorerDriver,IPhoneDriver, IPhoneSimulatorDriver,
RemoteWebDriver, SafariDriver
Steps for Creating class object with reference to interface
1. Choose the Browse on which you want to perform Automation and Select the
respective class to implement Webdriver
Ex: FirefoxDriver()
2. Create an object for the Class and assign name to it
Selenium=New FirefoxDriver();
3.Then make Class object reference to the Webdriver Interface which you want to
implement
Webdriver Selenium=New FirefoxDriver();
Basis methods of Webdriver:
Get();
Load a new web page in the current browser window.
getCurentURl();
Get a string representing the current URL that the browser is looking at.
getTitle()
The title of the current page
getPageSource()
Get the source of the last loaded page.
Quit():
Quits this driver, closing every associated window.
Close():Close the current window, quitting the browser if it's the last window
currently open.
Selenium - Capture Screenshots:

This functionality helps to grab screenshots at run time when required, in


particularly when a failure happens. With the help of screenshots and log
messages, we will be able to analyze the results better.
Screenshots are configured differently for local executions and Selenium
Grid(remote) executions. Let us take a look at each one them with an example.

Localhost Execution
In the following example, we will take a screenshot after calculating the percentage.
Ensure that you give a valid path to save the screenshot.
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
public class WebdriverDemo
{
public static void main(String[] args) throws IOException
{
WebDriver driver = new FirefoxDriver();
// Puts an Implicit wait, Will wait for 10 seconds before throwing exception
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Launch website
driver.navigate().to("http://www.calculator.net/");
// Maximize the browser
driver.manage().window().maximize();

// Click on Math Calculators


driver.findElement(By.xpath(".//*[@id='menu']/div[3]/a")).click();
// Click on Percent Calculators
driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/a")).click();
// Enter value 10 in the first number of the percent Calculator
driver.findElement(By.id("cpar1")).sendKeys("10");
// Enter value 50 in the second number of the percent Calculator
driver.findElement(By.id("cpar2")).sendKeys("50");
// Click Calculate Button
driver.findElement(By.xpath(".//*[@id='content']/table/tbody/tr/td[2]/input")).click();
// Get the Result Text based on its xpath
String result =
driver.findElement(By.xpath(".//*[@id='content']/p[2]/span/font/b")).getText();
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("D:\\screenshots\\screenshots1.jpg"));
// Print a Log In message to the screen
System.out.println(" The Result is " + result);
//Close the Browser.
driver.close();
}
}

Output
Upon executing the script, the screenshot is saved in the 'D:\screenshots' folder with
the name 'screenshots1.jpg' as shown below.

Accessing Links & Tables using Selenium Webdriver:


Links Matching a Criterion
Links can be accessed using an exact or partial match of their link text. The examples
below provide scenarios where multiple matches would exist, and would explain how
WebDriver would deal with them.
Exact Match
Accessing links using their exact link text is done through the By.linkText()
method. However, if there are two links that have the very same link text, this method
will only access the first one.
Case-sensitivity
The parameters for By.linkText() and By.partialLinkText() are both case-sensitive,
meaning that capitalization matters. For example, in Mercury Tours' homepage, there
are two links that contain the text "egis" - one is the "REGISTER" link found at the top
menu, and the other is the "Register here" link found at the lower right portion of the
page.

All Links
One of the common procedures in web testing is to test if all the links present within the
page are working. This can be conveniently done using a combination of the Java foreach loop and the By.tagName("a") method. The WebDriver code below checks each
link from the Mercury Tours homepage to determine those that are working and those
that are still under construction.
package practice_webdriver;
import java.util.List;

import
import
import
import
import

java.util.concurrent.TimeUnit;
org.openqa.selenium.*;
org.openqa.selenium.firefox.FirefoxDriver;
org.openqa.selenium.support.ui.ExpectedConditions;
org.openqa.selenium.support.ui.WebDriverWait;

public class AllLinks {


public static void main(String[] args) {
String baseUrl = "http://newtours.demoaut.com/";
WebDriver driver = new FirefoxDriver();
String underConsTitle = "Under Construction: Mercury Tours";
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get(baseUrl);
List<WebElement> linkElements = driver.findElements(By.tagName("a"));
String[] linkTexts = new String[linkElements.size()];
int i = 0;
//extract the link texts of each link element
for (WebElement e : linkElements) {
linkTexts[i] = e.getText();
i++;
}
//test each link
for (String t : linkTexts) {
driver.findElement(By.linkText(t)).click();
if (driver.getTitle().equals(underConsTitle)) {
System.out.println("\"" + t + "\""
+ " is under construction.");
} else {
System.out.println("\"" + t + "\""

+ " is working.");
}
driver.navigate().back();
}
driver.quit();
}
}

Links Outside and Inside a Block


The latest HTML5 standard allows the <a> tags to be placed inside and outside of blocklevel tags like <div>, <p>, or <h1>. The "By.linkText()" and "By.partialLinkText()"
methods can access a link located outside and inside these block-level elements.
Accessing Image Links
Image links are images that act as references to other sites or sections within the same
page. Since they are images, we cannot use the By.linkText() and By.partialLinkText()
methods because image links basically have no link texts at all. In this case, we should
resort to using either By.cssSelector or By.xpath. The first method is more preferred
because of its simplicity.

package practice_webdriver;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ImageLink {
public static void main(String[] args) {
String baseUrl = "https://www.facebook.com/login/identify?ctx=recover";
WebDriver driver = new FirefoxDriver();
driver.get(baseUrl);
//click on the "Facebook" logo on the upper left portion
driver.findElement(By.cssSelector("a[title=\"Go to Facebook Home\"]")).click();
//verify that we are now back on Facebook's homepage

if (driver.getTitle().equals("Welcome to Facebook - Log In, Sign Up or Learn


More")) {
System.out.println("We are back at Facebook's homepage");
} else {
System.out.println("We are NOT in Facebook's homepage");
}
driver.quit();
}
}

Reading a Table
There are times when we need to access elements (usually texts) that are within HTML
tables. However, it is very seldom for a web designer to provide an id or name attribute
to a certain cell in the table. Therefore, we cannot use the usual methods such as
"By.id()", "By.name()", or "By.cssSelector()". In this case, the most reliable option is to
access them using the "By.xpath()" method.

Need of Session Handling:


During test execution, the Selenium WebDriver has to interact with the browser all the
time to execute given commands. At the time of execution, it is also possible that,
before current execution completes, someone else starts execution of another script ,in
the same machine and in the same type of browser.
Achieve Session Handling in Selenium WebDriver:
If you check the source code of Selenium WebDriver, you will find a variable named as
'sessionId'. Whenever we create a new instance of WebDriver object, a new 'sessionId'
will be generated and attached with that particular Firefox/Chrome/IE Driver ().

So anything we do after this will execute only in that particular Firefox browser session.

As this is an in-built functionality, there is no explicit need to assign the session id


Code Example: Here two different sessions will be generate for two different WebDriver.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class SessionHandling {
public static void main(String...strings ){
//First session of WebDriver
WebDriver driver = new FirefoxDriver();
//Goto guru99 site
driver.get("https://facebook-com-p.surfly.com/www/ST/m2zs6ylgcRUGPu");
//Second session of WebDriver
WebDriver driver2 = new FirefoxDriver();
//Goto guru99 site
driver2.get("https://facebook-com-p.surfly.com/www/ST/m2zs6ylgcRUGPu");
}
}
Run Scripts in Parallel
There are situations where you want to run multiple tests at the same time.

In such cases one can use "parallel" attribute

The parallel attribute of suite tag can accept four values:


Run Scripts in Parallel
There are situations where you want to run multiple tests at the same time.
In such cases one can use "parallel" attribute

The parallel attribute of suite tag can accept four values:

tests

All the test cases inside <test> tag of testing xml file will run parallel.

classes

All the test cases inside a java class will run parallel

methods

All the methods with @Test annotation will execute parallel.

instances

Test cases in same instance will execute parallel but two methods of two different in
will run in different thread.

The attribute thread-count allows you to specify how many threads should be allocated
for this execution.

Complete Example: In this Example three test cases will run parallel and fill login data
in http://demo.guru99.com
Complete project will looks like:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class TestGuru99MultipleSession {
@Test
public void executSessionOne(){
//First session of WebDriver
System.setProperty("webdriver.chrome.driver","chromedriver.exe");
WebDriver driver = new ChromeDriver();
//Goto guru99 site
driver.get("https://facebook-com-p.surfly.com/www/ST/m2zs6ylgcRUGPu");
//find user name text box and fill it
driver.findElement(By.name("uid")).sendKeys("Driver 1");
}
@Test
public void executeSessionTwo(){

//Second session of WebDriver


System.setProperty("webdriver.chrome.driver","chromedriver.exe");
WebDriver driver = new ChromeDriver();
//Goto guru99 site
driver.get("https://facebook-com-p.surfly.com/www/ST/m2zs6ylgcRUGPu");
//find user name text box and fill it
driver.findElement(By.name("uid")).sendKeys("Driver 2");
}
@Test
public void executSessionThree(){
//Third session of WebDriver
System.setProperty("webdriver.chrome.driver","chromedriver.exe");
WebDriver driver = new ChromeDriver();
//Goto guru99 site
driver.get("https://facebook-com-p.surfly.com/www/ST/m2zs6ylgcRUGPu");
//find user name text box and fill it
driver.findElement(By.name("uid")).sendKeys("Driver 3");
}
}

Anda mungkin juga menyukai