SlideShare a Scribd company logo
Selenium Introduction
Prepared By:
Er. Sandeep Sharda
Sr. Member Technical Staff, OSB
Oracle
• Selenium IDE (SIDE)
• Selenium 1.0 (Remote Control)
• Selenium 2.0 (WebDriver)
• Selenium Grid
Selenium - Suite
• It is implemented as a Firefox extension, and allow us to
record, edit, and replay the test in Firefox
• We can save tests as HTML, Java, C# or any other format
by supported/available code formatter ext.
• Give facility to add assertions to verify results
• Allow to add selenese commands as and when required
• Selenium commands, often called selenese like: clicking
button, entering text, marking check box, selection from
list etc.
Selenium IDE
• IDE recorded test cases can run only in Firefox
• No Programming logic (like loops, conditional
statements) can be applied
• Selenium IDE can only execute scripts created in
Selenes
• It is difficult to use Selenium IDE for checking
complex test cases involving dynamic contents
Limitations of Selenium IDE
• It is a API and Library of Selenium
• A server, written in Java so can work in cross platforms
• A solution to cross browser testing
• Acts as a proxy to send web requests by launching browser
• Client libraries for many popular languages, to get support we need to
configure first
• We need to create the selenium object by giving server and browser
details to before running test cases:
DefaultSelenium selenium=new DefaultSelenium(“System address”, ”Port
no of selenium”, “Browser to launch”, “url”);
• This selenium object provide us interface to perform keyboard and
mouse action on keyboard
Selenium 1.0 (RC)
Selenium 2.0
WebDriver
What’s new
• Selenium 2.0 also called Selenium Web Driver
• Web Drivers are interfaces with language bindings
• WebDrivers are browser specific implementations
• Native keyboard and mouse interactions are supported
• Better support for handling popups and dialogs
• Supports running tests in mobile devices
• No need to start Selenium server unlike Selenium 1.0/RC
• WebDrivers available for language bindings – C#, Java,
Python, Perl, Ruby, PHP
Expr Desc Example
/ Select from the root node html/body/form/div[1]/center/table
/tbody/tr/td[1]/input
// Select nodes form the current node //table/tbody/tr/td[1]/input
@ Select attribute //input[@name=‘Login’]
Locating elements in Selenium
Through the HTML.. by
1. Tag name – a, input, select, span, div
2. Attribute – Name, Value, Id, type
3. Text - <title>Title of the document</title>
By Xpath
Example Desc
//input[@id='firstname’] Select element with tag input and id=firstname
//input[contains(text(),’Gmo ')] Select element with text containing Gmo
//input[starts-with(text(),’Enter’)] Select element with text starting with Enter
//input[contains(@value, “GMO")] identify element containing ‘GMO’ in value attribute
//input[contains(@id, "searchInput")
and contains(@text,“google")]
look at two attributes in input node
//input[starts-with(@type, “s")] find input node with attribute type and its value is starting
with 's'
//*[@accesskey=‘alpha'] Can use wild cards
//input[text()='First Name:'] Select element with tag input and text=firstname
//td/a/strong[contains(text(),'Socks')] Find all elements containing ‘Socks’
Examples: Locating elements
by Xpath
More: http://www.w3schools.com/xpath/xpath_syntax.asp
Selector Sample Desc
.Class .Button Selects all elements with class=“Button"
#Id #myForm Selects the element with id="myForm"
Element Select Selects all <select> elements
element, element Select , option elects all <select> and all <option> elements
element element Select option Selects all <select> elements inside <option>
elements
[attribute=value] [size='22'] Selects all elements with size=“22”
Element:first-child Select:first-child Select every <Select> element that is the first
child of its parent
Element:nth-child(n) Select:nth-child(2) Selects every <Select> element that is the second
child of its parent
Element:last-child Select:last-child Selects every <Select> element that is the last
child of its parent
Element:checked input:checked
Examples: Locating elements
by Css Selector
More: http://www.w3schools.com/cssref/css_selectors.asp
• Firefox
ff=new FirefoxDriver();
• IE
System.setProperty("webdriver.ie.driver", “D:Selenium
ProjectsBrowserDriversIEDriverServer.exe");
ie=new InternetExplorerDriver();
//ensure protected mode is turned off/on for all zones under security tab
//set zoom level to 100%
• Chrome
System.setProperty("webdriver.chrome.driver", "D:Selenium
ProjectsBrowserDriverschromedriver.exe");
chrome=new ChromeDriver();
//ensure auto update is turned off
Working with Browsers
Method Desc
.get(String url) Navigate to url
.navigate().to(String url) Navigate to url
.navigate().back() Navigate to the previous page in thecache
.navigate().forward() Navigate to the next page in thecache
.getTitle() Pagetitle
.close() Close the current instance of thebrowser
.quit() Close all instances of thebrowser
.findElement(By.xpath(xp)) Locate element byxpath
.findElement(By.name(name)) Locate element by nameattribute
.findElement(By.id(id)) Locate element by idattribute
.findElement(By.className(cls)) Locate element byclass
.findElement(By.cssSelector(selector)) Locate element by cssselector
.findElements(By.tagName(tagname)) Locate all elements having tagtagname
Commonly used WebDriver
methods
Method Desc
element.getText() Retrieves the text of the givenelement
element.clear() Clears the value from inputelement
element.sendKeys(chars) Input value into element
.manage().window().maximize(); Maximize window
.manage().timeouts().pageLoadTimeout
(10,TimeUnit.SECONDS);
Page load time
element.isDisplayed() Check if element is displayed – returnstrue/false
element.isEnabled() Check if element is enabled– returnstrue/false
Commonly used WebDriver
methods
• Input field
WebElement field = driver.findElement(By.name("QTY_TENTS"));
field.clear(); field.sendKeys(value);
• Drop Down box
Select selection = new Select(browserDriver.findElement(By.xpath("//select[@name='CardType']“));
List<WebElement> options = selection.getOptions(); elementSize=options.size();
selection.selectByIndex(1); / selection.selectByVisibleText(“visa”);
• Radio
driver.findElement(By.xpath("//input[@value='oneway']")).click();
• Check box
isChecked=driver.findElement(By.name("shipSameAsBill")).isSelected();
driver.findElement(By.name("shipSameAsBill")).click();
• Handle popups
driver.switchTo().alert().accept(); driver.switchTo().alert().getText();
WebDriver Snippets
• Auto-suggest Drop down (google.co.in)
driver.findElement(By.cssSelector(“. gbqfqw").sendKeys(value);
driver.findElement(By.cssSelector(“#gbqfqw").sendKeys(Keys.DOWN);
driver.findElement(By.cssSelector(“div#gbqfqw”).sendKeys(Keys.UP);
• List out the options in the selection box
WebElement select = driver.findElement(By.name('CardType'));
List <WebElement> options = select.findElements(By.tagName("option"));
for (WebElement option : options) {
String name = option.getAttribute("value"); System.out.println("value:"+name); }
• Switch to frame
driver.switchTo().frame( "frameName" ); driver.switchTo().defaultContent();
• Handling Windows
Set<String> handles = driver.getWindowHandles(); nextWindowHandle=handles().iterator().next();
driver.switchTo().window(nextWindowHandle);
WebDriver Snippets
• Capture screen shot
File scrFile = ((TakesScreenshot) browserDriver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(“c:.filename.jpg"));
• Wait for an element – Explicit wait
WebDriverWait wait = new WebDriverWait(browserDriver, 10); //seconds
WebElement ele = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath ("//a[contains(text(),'Java
training')]")));
• Implicit Wait – applies to all elements
browserDriver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
• Simulate mouse actions
Actions mouseAction= new Actions(driver);
WebElement menu = wd.findElement(By.xpath("//a/span[text()= 'Books & Media']"));
mouseAction.moveToElement(menu).perform();
WebDriver Snippets
WebDriver Snippets
• Execute Java Script
((JavascriptExecutor) driver).executeScript(<any valid javascript>);
• Co-ordinates of WebElement
WebElement techEval=driver.findElement(By.xpath("//a[text()='Technical topics']"));
Method 1
Locatable hoverItem = (Locatable) techEval;
Coordinates cor= hoverItem.getCoordinates(); System.out.println(cor);
Method 2
System.out.println(techEval.getLocation().getX() +”,“ +techEval.getLocation().getY());
Firefox profile
• A profile in Firefox is a collection of bookmarks, browser settings,
extensions, passwords, and history; all of personal settings.
• Why use profile when executing selenium tests?
• Webdriver always creates an anonymous profile with default settings,
so sometimes tests may behave differently at times
• Tests may require some proxy settings which doesnot come with default
settings which webdriver creates.
• SSL certificates or some browser plugins may be required to successfully
execute the tests.
• Procedure:
• Create a new profile and use in the test
• Create firefox profile through script
• Create a new profile and use in the test
• From windows start/run : firefox.exe -P
• Create a new profile. Select the profile, start firefox, apply settings.
• In selenium script, code the following and examine new firefox browser is opened with
applied settings.
ProfilesIni pi = new ProfilesIni(); FirefoxProfile fp = pi.getProfile("SelTests");
browserDriver=new FirefoxDriver(fp);
• Create firefox profile through script with proxy settings
FirefoxProfile fp = new FirefoxProfile(); fp.setEnableNativeEvents(true);
fp.setPreference("network.proxy.type", 1); // manual proxy setting
fp.setPreference("network.proxy.http", "localhost"); // specify ip (or localhost)
fp.setPreference("network.proxy.http_port", 8080); // specify port
browserDriver=new FirefoxDriver(fp);
Get these properties by typing “about:config” in Firefox browser
Firefox profile
Exceptions Desc
ElementNotVisibleException Thrown when although an element is present on the DOM,
it is not visible, and so is not able to be interacted with.
NoAlertPresentException Thrown when switching to alert which is not present.
NoSuchElementException Thrown when element could not be found.
TimeoutException Thrown when a command does not complete in enough
time.
UnexpectedAlertPresentExceptio
n
Thrown when an unexpected alert is appeared.
StaleElementReferenceException Thrown when a reference to an element no longer appears
on the DOM
ElementNotFoundException page not loading fast enough or element not yet loaded
Selenium Exceptions
Grid 2.0
• Run tests in parallel
• Run tests in multiple machines – Physical/Virtual
• Consists of hub and one or more nodes
• Hub
• provides the configurations or capabilities to the Selenium
WebDriver tests
• receive the entire test request and distribute it to the right
nodes
• Nodes
• connects to hub for parallel execution
Grid Configuration
• Hub m/c
Standalone jar run as hub
Listens to configured nodes on port 4444 (default and can be
changed)
java –jar selenium-server-standalone-2.xx.x.jar –role hub [-port xxxx]
• Nodes m/c
Standalone jar run as node with browser, OS configuration with any
open port
• Execute
Run the test code from eclipse/IntelliJ or supported IDE
Node Configuration
• IE
java -jar selenium-server-standalone-2.xx.x.jar -role webdriver -port 5555
-Dwebdriver.ie.driver=C:BrowserDriversIEDriverServer.exe
-browser “browserName=iexplore,version=8,maxinstance=1,platform=WINDOWS"
-hub http://hub_IP_or_Name:4444/grid/register
• Chrome
java -jar selenium-server-standalone-2.xx.x.jar -role webdriver -port 5555
-Dwebdriver.chrome.driver=C:BrowserDriverschromedriver.exe
-browser "browserName=chrome,version=28,maxinstance=1,platform=WINDOWS"
-hub http://hub_IP_or_Name:4444/grid/register
• With Firefox
java -jar selenium-server-standalone-2.xx.x.jar -role webdriver –port 5555
-browser "browserName=firefox, version=22,maxinstance=2,platform=ANY"
-hub http://hub_IP_or_Name:4444/grid/register
• From IntelliJ
• Add TestNg jar file to libraries
• Create TestNg test class and create test code methods with relevant
TestNg annotations
• Run the test code using TestNg test
• Using Testng.xml
• Create testng.xml – manual
• Create testng.xml - Eclipse-TestNg needs to configured in eclipse
• Run the xml file
‒ From command line
‒ From Ant – download/configure Ant from within eclipse
‒ From Maven – download/configure Maven from within eclipse
Grid - Test Execution via
TestNG
Thank you

More Related Content

What's hot

Basic Selenium Training
Basic Selenium TrainingBasic Selenium Training
Basic Selenium Training
Dipesh Bhatewara
 
Automation Testing using Selenium Webdriver
Automation Testing using Selenium WebdriverAutomation Testing using Selenium Webdriver
Automation Testing using Selenium Webdriver
Pankaj Biswas
 
Testing mit Codeception: Full-stack testing PHP framework
Testing mit Codeception: Full-stack testing PHP frameworkTesting mit Codeception: Full-stack testing PHP framework
Testing mit Codeception: Full-stack testing PHP framework
SusannSgorzaly
 
Selenium Automation Using Ruby
Selenium Automation Using RubySelenium Automation Using Ruby
Selenium Automation Using RubyKumari Warsha Goel
 
Foundation selenium java
Foundation selenium java Foundation selenium java
Foundation selenium java
seleniumbootcamp
 
Selenium presentation
Selenium presentationSelenium presentation
Selenium presentation
P.V.G'S COET, PUNE - 09
 
Automated Testing With Watir
Automated Testing With WatirAutomated Testing With Watir
Automated Testing With Watir
Timothy Fisher
 
Selenium WebDriver FAQ's
Selenium WebDriver FAQ'sSelenium WebDriver FAQ's
Selenium WebDriver FAQ's
Praveen Gorantla
 
How to Configure Selenium WebDriver (java)
How to Configure Selenium WebDriver (java)How to Configure Selenium WebDriver (java)
How to Configure Selenium WebDriver (java)
Dasun Eranthika
 
Selenium
SeleniumSelenium
Selenium
Purna Chandar
 
An overview of selenium webdriver
An overview of selenium webdriverAn overview of selenium webdriver
An overview of selenium webdriver
Anuraj S.L
 
Protractor framework – how to make stable e2e tests for Angular applications
Protractor framework – how to make stable e2e tests for Angular applicationsProtractor framework – how to make stable e2e tests for Angular applications
Protractor framework – how to make stable e2e tests for Angular applications
Ludmila Nesvitiy
 
Selenium using Java
Selenium using JavaSelenium using Java
Selenium using Java
F K
 
Introduction to Selenium Web Driver
Introduction to Selenium Web DriverIntroduction to Selenium Web Driver
Introduction to Selenium Web Driver
Return on Intelligence
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha Touch
Mats Bryntse
 
Automation Testing
Automation TestingAutomation Testing
Automation Testing
AbdulImrankhan7
 
DSL, Page Object and WebDriver – the path to reliable functional tests.pptx
DSL, Page Object and WebDriver – the path to reliable functional tests.pptxDSL, Page Object and WebDriver – the path to reliable functional tests.pptx
DSL, Page Object and WebDriver – the path to reliable functional tests.pptx
Mikalai Alimenkou
 
Selenium Interview Questions and Answers | Selenium Tutorial | Selenium Train...
Selenium Interview Questions and Answers | Selenium Tutorial | Selenium Train...Selenium Interview Questions and Answers | Selenium Tutorial | Selenium Train...
Selenium Interview Questions and Answers | Selenium Tutorial | Selenium Train...
Edureka!
 

What's hot (20)

Basic Selenium Training
Basic Selenium TrainingBasic Selenium Training
Basic Selenium Training
 
Automation Testing using Selenium Webdriver
Automation Testing using Selenium WebdriverAutomation Testing using Selenium Webdriver
Automation Testing using Selenium Webdriver
 
Testing mit Codeception: Full-stack testing PHP framework
Testing mit Codeception: Full-stack testing PHP frameworkTesting mit Codeception: Full-stack testing PHP framework
Testing mit Codeception: Full-stack testing PHP framework
 
Selenium Automation Using Ruby
Selenium Automation Using RubySelenium Automation Using Ruby
Selenium Automation Using Ruby
 
Foundation selenium java
Foundation selenium java Foundation selenium java
Foundation selenium java
 
Selenium presentation
Selenium presentationSelenium presentation
Selenium presentation
 
Automated Testing With Watir
Automated Testing With WatirAutomated Testing With Watir
Automated Testing With Watir
 
Selenium WebDriver FAQ's
Selenium WebDriver FAQ'sSelenium WebDriver FAQ's
Selenium WebDriver FAQ's
 
How to Configure Selenium WebDriver (java)
How to Configure Selenium WebDriver (java)How to Configure Selenium WebDriver (java)
How to Configure Selenium WebDriver (java)
 
Selenium
SeleniumSelenium
Selenium
 
An overview of selenium webdriver
An overview of selenium webdriverAn overview of selenium webdriver
An overview of selenium webdriver
 
Protractor framework – how to make stable e2e tests for Angular applications
Protractor framework – how to make stable e2e tests for Angular applicationsProtractor framework – how to make stable e2e tests for Angular applications
Protractor framework – how to make stable e2e tests for Angular applications
 
Selenium drivers
Selenium driversSelenium drivers
Selenium drivers
 
Selenium using Java
Selenium using JavaSelenium using Java
Selenium using Java
 
Introduction to Selenium Web Driver
Introduction to Selenium Web DriverIntroduction to Selenium Web Driver
Introduction to Selenium Web Driver
 
Selenium Concepts
Selenium ConceptsSelenium Concepts
Selenium Concepts
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha Touch
 
Automation Testing
Automation TestingAutomation Testing
Automation Testing
 
DSL, Page Object and WebDriver – the path to reliable functional tests.pptx
DSL, Page Object and WebDriver – the path to reliable functional tests.pptxDSL, Page Object and WebDriver – the path to reliable functional tests.pptx
DSL, Page Object and WebDriver – the path to reliable functional tests.pptx
 
Selenium Interview Questions and Answers | Selenium Tutorial | Selenium Train...
Selenium Interview Questions and Answers | Selenium Tutorial | Selenium Train...Selenium Interview Questions and Answers | Selenium Tutorial | Selenium Train...
Selenium Interview Questions and Answers | Selenium Tutorial | Selenium Train...
 

Similar to Selenium Introduction by Sandeep Sharda

Selenium.pptx
Selenium.pptxSelenium.pptx
Selenium.pptx
orbitprojects
 
Selenium web driver
Selenium web driverSelenium web driver
Selenium web driver
Sun Technlogies
 
Selenium
SeleniumSelenium
Selenium
Ruturaj Doshi
 
Selenium
SeleniumSelenium
Selenium
Sun Technlogies
 
Selenium Tutorial for Beginners - TIB Academy
Selenium Tutorial for Beginners - TIB AcademySelenium Tutorial for Beginners - TIB Academy
Selenium Tutorial for Beginners - TIB Academy
TIB Academy
 
Selenium Automation
Selenium AutomationSelenium Automation
Selenium Automation
Pratyush Majumdar
 
Automated ui-testing
Automated ui-testingAutomated ui-testing
Automated ui-testing
Slobodan Lohja
 
Automated ui testing with selenium. drupal con london 2011
Automated ui testing with selenium. drupal con london 2011Automated ui testing with selenium. drupal con london 2011
Automated ui testing with selenium. drupal con london 2011
Yuriy Gerasimov
 
Mastering Test Automation: How To Use Selenium Successfully
Mastering Test Automation: How To Use Selenium SuccessfullyMastering Test Automation: How To Use Selenium Successfully
Mastering Test Automation: How To Use Selenium Successfully
SpringPeople
 
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!
Puneet Kala
 
Selenium
SeleniumSelenium
Selenium
eduquer
 
Selenium
SeleniumSelenium
Selenium
mdfkhan625
 
selenium.ppt
selenium.pptselenium.ppt
selenium.ppt
rajnexient
 
Selenium web driver
Selenium web driverSelenium web driver
Selenium web driver
Roman Savitskiy
 
Selenium - Introduction
Selenium - IntroductionSelenium - Introduction
Selenium - Introduction
Amr E. Mohamed
 
selenium.ppt
selenium.pptselenium.ppt
selenium.ppt
ssuser7b4894
 
selenium.ppt
selenium.pptselenium.ppt
selenium.ppt
AmenSheikh
 
Get Started With Selenium 3 and Selenium 3 Grid
Get Started With Selenium 3 and Selenium 3 GridGet Started With Selenium 3 and Selenium 3 Grid
Get Started With Selenium 3 and Selenium 3 Grid
Daniel Herken
 
full-stack-webapp-testing-with-selenium-and-rails.pdf
full-stack-webapp-testing-with-selenium-and-rails.pdffull-stack-webapp-testing-with-selenium-and-rails.pdf
full-stack-webapp-testing-with-selenium-and-rails.pdf
Brian Takita
 
Selenium Tutorial
Selenium TutorialSelenium Tutorial
Selenium Tutorialprad_123
 

Similar to Selenium Introduction by Sandeep Sharda (20)

Selenium.pptx
Selenium.pptxSelenium.pptx
Selenium.pptx
 
Selenium web driver
Selenium web driverSelenium web driver
Selenium web driver
 
Selenium
SeleniumSelenium
Selenium
 
Selenium
SeleniumSelenium
Selenium
 
Selenium Tutorial for Beginners - TIB Academy
Selenium Tutorial for Beginners - TIB AcademySelenium Tutorial for Beginners - TIB Academy
Selenium Tutorial for Beginners - TIB Academy
 
Selenium Automation
Selenium AutomationSelenium Automation
Selenium Automation
 
Automated ui-testing
Automated ui-testingAutomated ui-testing
Automated ui-testing
 
Automated ui testing with selenium. drupal con london 2011
Automated ui testing with selenium. drupal con london 2011Automated ui testing with selenium. drupal con london 2011
Automated ui testing with selenium. drupal con london 2011
 
Mastering Test Automation: How To Use Selenium Successfully
Mastering Test Automation: How To Use Selenium SuccessfullyMastering Test Automation: How To Use Selenium Successfully
Mastering Test Automation: How To Use Selenium Successfully
 
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!
 
Selenium
SeleniumSelenium
Selenium
 
Selenium
SeleniumSelenium
Selenium
 
selenium.ppt
selenium.pptselenium.ppt
selenium.ppt
 
Selenium web driver
Selenium web driverSelenium web driver
Selenium web driver
 
Selenium - Introduction
Selenium - IntroductionSelenium - Introduction
Selenium - Introduction
 
selenium.ppt
selenium.pptselenium.ppt
selenium.ppt
 
selenium.ppt
selenium.pptselenium.ppt
selenium.ppt
 
Get Started With Selenium 3 and Selenium 3 Grid
Get Started With Selenium 3 and Selenium 3 GridGet Started With Selenium 3 and Selenium 3 Grid
Get Started With Selenium 3 and Selenium 3 Grid
 
full-stack-webapp-testing-with-selenium-and-rails.pdf
full-stack-webapp-testing-with-selenium-and-rails.pdffull-stack-webapp-testing-with-selenium-and-rails.pdf
full-stack-webapp-testing-with-selenium-and-rails.pdf
 
Selenium Tutorial
Selenium TutorialSelenium Tutorial
Selenium Tutorial
 

Selenium Introduction by Sandeep Sharda

  • 1. Selenium Introduction Prepared By: Er. Sandeep Sharda Sr. Member Technical Staff, OSB Oracle
  • 2. • Selenium IDE (SIDE) • Selenium 1.0 (Remote Control) • Selenium 2.0 (WebDriver) • Selenium Grid Selenium - Suite
  • 3. • It is implemented as a Firefox extension, and allow us to record, edit, and replay the test in Firefox • We can save tests as HTML, Java, C# or any other format by supported/available code formatter ext. • Give facility to add assertions to verify results • Allow to add selenese commands as and when required • Selenium commands, often called selenese like: clicking button, entering text, marking check box, selection from list etc. Selenium IDE
  • 4. • IDE recorded test cases can run only in Firefox • No Programming logic (like loops, conditional statements) can be applied • Selenium IDE can only execute scripts created in Selenes • It is difficult to use Selenium IDE for checking complex test cases involving dynamic contents Limitations of Selenium IDE
  • 5. • It is a API and Library of Selenium • A server, written in Java so can work in cross platforms • A solution to cross browser testing • Acts as a proxy to send web requests by launching browser • Client libraries for many popular languages, to get support we need to configure first • We need to create the selenium object by giving server and browser details to before running test cases: DefaultSelenium selenium=new DefaultSelenium(“System address”, ”Port no of selenium”, “Browser to launch”, “url”); • This selenium object provide us interface to perform keyboard and mouse action on keyboard Selenium 1.0 (RC)
  • 7. What’s new • Selenium 2.0 also called Selenium Web Driver • Web Drivers are interfaces with language bindings • WebDrivers are browser specific implementations • Native keyboard and mouse interactions are supported • Better support for handling popups and dialogs • Supports running tests in mobile devices • No need to start Selenium server unlike Selenium 1.0/RC • WebDrivers available for language bindings – C#, Java, Python, Perl, Ruby, PHP
  • 8. Expr Desc Example / Select from the root node html/body/form/div[1]/center/table /tbody/tr/td[1]/input // Select nodes form the current node //table/tbody/tr/td[1]/input @ Select attribute //input[@name=‘Login’] Locating elements in Selenium Through the HTML.. by 1. Tag name – a, input, select, span, div 2. Attribute – Name, Value, Id, type 3. Text - <title>Title of the document</title> By Xpath
  • 9. Example Desc //input[@id='firstname’] Select element with tag input and id=firstname //input[contains(text(),’Gmo ')] Select element with text containing Gmo //input[starts-with(text(),’Enter’)] Select element with text starting with Enter //input[contains(@value, “GMO")] identify element containing ‘GMO’ in value attribute //input[contains(@id, "searchInput") and contains(@text,“google")] look at two attributes in input node //input[starts-with(@type, “s")] find input node with attribute type and its value is starting with 's' //*[@accesskey=‘alpha'] Can use wild cards //input[text()='First Name:'] Select element with tag input and text=firstname //td/a/strong[contains(text(),'Socks')] Find all elements containing ‘Socks’ Examples: Locating elements by Xpath More: http://www.w3schools.com/xpath/xpath_syntax.asp
  • 10. Selector Sample Desc .Class .Button Selects all elements with class=“Button" #Id #myForm Selects the element with id="myForm" Element Select Selects all <select> elements element, element Select , option elects all <select> and all <option> elements element element Select option Selects all <select> elements inside <option> elements [attribute=value] [size='22'] Selects all elements with size=“22” Element:first-child Select:first-child Select every <Select> element that is the first child of its parent Element:nth-child(n) Select:nth-child(2) Selects every <Select> element that is the second child of its parent Element:last-child Select:last-child Selects every <Select> element that is the last child of its parent Element:checked input:checked Examples: Locating elements by Css Selector More: http://www.w3schools.com/cssref/css_selectors.asp
  • 11. • Firefox ff=new FirefoxDriver(); • IE System.setProperty("webdriver.ie.driver", “D:Selenium ProjectsBrowserDriversIEDriverServer.exe"); ie=new InternetExplorerDriver(); //ensure protected mode is turned off/on for all zones under security tab //set zoom level to 100% • Chrome System.setProperty("webdriver.chrome.driver", "D:Selenium ProjectsBrowserDriverschromedriver.exe"); chrome=new ChromeDriver(); //ensure auto update is turned off Working with Browsers
  • 12. Method Desc .get(String url) Navigate to url .navigate().to(String url) Navigate to url .navigate().back() Navigate to the previous page in thecache .navigate().forward() Navigate to the next page in thecache .getTitle() Pagetitle .close() Close the current instance of thebrowser .quit() Close all instances of thebrowser .findElement(By.xpath(xp)) Locate element byxpath .findElement(By.name(name)) Locate element by nameattribute .findElement(By.id(id)) Locate element by idattribute .findElement(By.className(cls)) Locate element byclass .findElement(By.cssSelector(selector)) Locate element by cssselector .findElements(By.tagName(tagname)) Locate all elements having tagtagname Commonly used WebDriver methods
  • 13. Method Desc element.getText() Retrieves the text of the givenelement element.clear() Clears the value from inputelement element.sendKeys(chars) Input value into element .manage().window().maximize(); Maximize window .manage().timeouts().pageLoadTimeout (10,TimeUnit.SECONDS); Page load time element.isDisplayed() Check if element is displayed – returnstrue/false element.isEnabled() Check if element is enabled– returnstrue/false Commonly used WebDriver methods
  • 14. • Input field WebElement field = driver.findElement(By.name("QTY_TENTS")); field.clear(); field.sendKeys(value); • Drop Down box Select selection = new Select(browserDriver.findElement(By.xpath("//select[@name='CardType']“)); List<WebElement> options = selection.getOptions(); elementSize=options.size(); selection.selectByIndex(1); / selection.selectByVisibleText(“visa”); • Radio driver.findElement(By.xpath("//input[@value='oneway']")).click(); • Check box isChecked=driver.findElement(By.name("shipSameAsBill")).isSelected(); driver.findElement(By.name("shipSameAsBill")).click(); • Handle popups driver.switchTo().alert().accept(); driver.switchTo().alert().getText(); WebDriver Snippets
  • 15. • Auto-suggest Drop down (google.co.in) driver.findElement(By.cssSelector(“. gbqfqw").sendKeys(value); driver.findElement(By.cssSelector(“#gbqfqw").sendKeys(Keys.DOWN); driver.findElement(By.cssSelector(“div#gbqfqw”).sendKeys(Keys.UP); • List out the options in the selection box WebElement select = driver.findElement(By.name('CardType')); List <WebElement> options = select.findElements(By.tagName("option")); for (WebElement option : options) { String name = option.getAttribute("value"); System.out.println("value:"+name); } • Switch to frame driver.switchTo().frame( "frameName" ); driver.switchTo().defaultContent(); • Handling Windows Set<String> handles = driver.getWindowHandles(); nextWindowHandle=handles().iterator().next(); driver.switchTo().window(nextWindowHandle); WebDriver Snippets
  • 16. • Capture screen shot File scrFile = ((TakesScreenshot) browserDriver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile, new File(“c:.filename.jpg")); • Wait for an element – Explicit wait WebDriverWait wait = new WebDriverWait(browserDriver, 10); //seconds WebElement ele = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath ("//a[contains(text(),'Java training')]"))); • Implicit Wait – applies to all elements browserDriver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS); • Simulate mouse actions Actions mouseAction= new Actions(driver); WebElement menu = wd.findElement(By.xpath("//a/span[text()= 'Books & Media']")); mouseAction.moveToElement(menu).perform(); WebDriver Snippets
  • 17. WebDriver Snippets • Execute Java Script ((JavascriptExecutor) driver).executeScript(<any valid javascript>); • Co-ordinates of WebElement WebElement techEval=driver.findElement(By.xpath("//a[text()='Technical topics']")); Method 1 Locatable hoverItem = (Locatable) techEval; Coordinates cor= hoverItem.getCoordinates(); System.out.println(cor); Method 2 System.out.println(techEval.getLocation().getX() +”,“ +techEval.getLocation().getY());
  • 18. Firefox profile • A profile in Firefox is a collection of bookmarks, browser settings, extensions, passwords, and history; all of personal settings. • Why use profile when executing selenium tests? • Webdriver always creates an anonymous profile with default settings, so sometimes tests may behave differently at times • Tests may require some proxy settings which doesnot come with default settings which webdriver creates. • SSL certificates or some browser plugins may be required to successfully execute the tests. • Procedure: • Create a new profile and use in the test • Create firefox profile through script
  • 19. • Create a new profile and use in the test • From windows start/run : firefox.exe -P • Create a new profile. Select the profile, start firefox, apply settings. • In selenium script, code the following and examine new firefox browser is opened with applied settings. ProfilesIni pi = new ProfilesIni(); FirefoxProfile fp = pi.getProfile("SelTests"); browserDriver=new FirefoxDriver(fp); • Create firefox profile through script with proxy settings FirefoxProfile fp = new FirefoxProfile(); fp.setEnableNativeEvents(true); fp.setPreference("network.proxy.type", 1); // manual proxy setting fp.setPreference("network.proxy.http", "localhost"); // specify ip (or localhost) fp.setPreference("network.proxy.http_port", 8080); // specify port browserDriver=new FirefoxDriver(fp); Get these properties by typing “about:config” in Firefox browser Firefox profile
  • 20. Exceptions Desc ElementNotVisibleException Thrown when although an element is present on the DOM, it is not visible, and so is not able to be interacted with. NoAlertPresentException Thrown when switching to alert which is not present. NoSuchElementException Thrown when element could not be found. TimeoutException Thrown when a command does not complete in enough time. UnexpectedAlertPresentExceptio n Thrown when an unexpected alert is appeared. StaleElementReferenceException Thrown when a reference to an element no longer appears on the DOM ElementNotFoundException page not loading fast enough or element not yet loaded Selenium Exceptions
  • 21. Grid 2.0 • Run tests in parallel • Run tests in multiple machines – Physical/Virtual • Consists of hub and one or more nodes • Hub • provides the configurations or capabilities to the Selenium WebDriver tests • receive the entire test request and distribute it to the right nodes • Nodes • connects to hub for parallel execution
  • 22. Grid Configuration • Hub m/c Standalone jar run as hub Listens to configured nodes on port 4444 (default and can be changed) java –jar selenium-server-standalone-2.xx.x.jar –role hub [-port xxxx] • Nodes m/c Standalone jar run as node with browser, OS configuration with any open port • Execute Run the test code from eclipse/IntelliJ or supported IDE
  • 23. Node Configuration • IE java -jar selenium-server-standalone-2.xx.x.jar -role webdriver -port 5555 -Dwebdriver.ie.driver=C:BrowserDriversIEDriverServer.exe -browser “browserName=iexplore,version=8,maxinstance=1,platform=WINDOWS" -hub http://hub_IP_or_Name:4444/grid/register • Chrome java -jar selenium-server-standalone-2.xx.x.jar -role webdriver -port 5555 -Dwebdriver.chrome.driver=C:BrowserDriverschromedriver.exe -browser "browserName=chrome,version=28,maxinstance=1,platform=WINDOWS" -hub http://hub_IP_or_Name:4444/grid/register • With Firefox java -jar selenium-server-standalone-2.xx.x.jar -role webdriver –port 5555 -browser "browserName=firefox, version=22,maxinstance=2,platform=ANY" -hub http://hub_IP_or_Name:4444/grid/register
  • 24. • From IntelliJ • Add TestNg jar file to libraries • Create TestNg test class and create test code methods with relevant TestNg annotations • Run the test code using TestNg test • Using Testng.xml • Create testng.xml – manual • Create testng.xml - Eclipse-TestNg needs to configured in eclipse • Run the xml file ‒ From command line ‒ From Ant – download/configure Ant from within eclipse ‒ From Maven – download/configure Maven from within eclipse Grid - Test Execution via TestNG