Selenium Webdriver

Introduction:

Selenium WebDriver is an API that allows us to write automated tests for web applications. The automated tests that use Selenium WebDriver are run by using a web browser. In other words, Selenium WebDriver helps us to verify that our application is working as expected when it is used by a real user. Selenium Web Driver Architecture:

Selenium Web driver architecture mainly divided into three parts

  1. Language level bindings
  2. Selenium Web driver API
  3. Drivers
Selenium Arthitecture
  • Language Level Bindings : Bindings refer to the language level bindings with which we can implement the Selenium Webdriver code. In simple words, these are the languages in which we can make a framework, which will interact with the Selenium Webdriver and work on various browsers and other devices. So we have a common API that has a common set of commands and we have various bindings for the different languages. Some Language level Bindings are Java, Java, Python, Ruby, there’s also some other bindings and new bindings can be added very easily.
  • Selenium Webdriver API: Selenium Webdriver API sends the commands taken from language level bindings interpret it and sent it to the Respective driver. In basic term, it contains set of a common library which allows sending a command to respective drivers.
  • Drivers: Drivers refer to various internet browsers such as IE driver, a Firefox, Chrome, and other drivers such as HTML unit which is an interesting one. It works in a headless mode which makes text execution faster. It also contains mobile specific drivers as well. So the Chrome driver knows how to handle the low-level details of Chrome browser and drive it to do things like clicking the button, going into pages, getting data from the browser itself, the same thing for Firefox, IE, and so on.

Install java in windows

  • Visit the Java website and download the installer
    • To install Java, you first need to download the installer program from Oracle. Follow the link mentioned below:
    • install java in windows
  • Navigate to Java SE Development Kit 8u211 as depicted in Image Below
Java_Install
Java_Install
  • Click on Accept License Agreement
  • Click on the Installer jdk-8u211-windows-x64.exe have selected it as we would be installing it on a 64-bit machine.
  • It will land you to Oracle Account Sign In Page
Oracle SignUp
  • In case you don't have an account you can sign up by clicking on Create Account
  • Fill in all Details as desired and it will Create a New Account
Oracle Account Creation
  • Post that you can log in and Installer will Install jdk-8u211-windows-x64.exe for your Machine.
  • Double click on that and it will Install Java on your Machine post clicking on Next Next buttons.
  • Steps for Validation that java is Installed on your Machine
      • Open Command Prompt(cmd)
      • and type java -version
Java_Validation
  • Congratulations now you have successfully Installed Java on your Machine.

Eclipse download for windows 10 64 bit

Neon Download -Automation Laboratories
  •  Click on Eclipse IDE for Java EE Developers.
 J2ee-Automation Laboratories
  •  Download depending on the bit size of your system.
Bit
  • Once it completes download right Click on the .zip file and extracts it.
  • After extraction Double click on the Eclipse Icon.
 Eclipse Icon
  • It will ask for the workspace location by default it creates the workspace in Documents you can change it as desired.
 Eclipse_Workspace
  • Click OK. Before installing eclipse ensure that you have installed latest JDK
For Java Installation follow the steps mentioned in Tab before.Note: to check Java version Installed open cmd and use the command: java -version java version
  • To Create new Maven Project Click on file ->New->Others->Maven Project and Click on Next.
 Maven_Project
  • Provide appropriate Details as required mentioned below:
 Creation
  • You may see Screen like below Now Right click on the project New->Package
 Automatin_package
  • Right-click on the Package->Click New Class
 Test_Class
  • After clicking finish you may screen like this.
 Test_Package

Dependency Injection of Selenium in Maven Project:

  1. In Pom.xml provide Selenium Dependency as shown in Snapshot below:
MavenDependency 2. Selenium Dependencies would be downloaded and can be viewed in Maven Dependencies. Maven Dependencies

Java topics for Selenium we need to cover.

Frequently Asked Questions:

  1. Is it complex to move from Manual testing to Automation?
  2. What concepts of Java do I need to learn to use selenium webdriver?
  3.  I am completely new to programming. Can I still learn Selenium?
  4.  What is the best source to learn Java from Scratch?
Kindly follow our Link for Best Java Explanation:Java

A complete list of Java topics for Selenium

  1.  Object Oriented Concept
  2. Class
  3. Object
  4. Inheritance
  5. Polymorphism
  6. Abstraction
  7. List of keywords, Interface in Java.
  8. Handle data types and usage of same.
  9. Control statements.
  10. Looping statements.
  11.  String class
  12. Arrays
  13. Exception handling.
  14. Collection framework (List, Set)
  15. File handling.
  16. Packages and Eclipse usages.
  • Open Browser:

For Testing Browser must be invoked.Selenium helps us to invoke the Browser so that we can perform required operations:

Command to invoke Browser:

WebDriver driver=new FirefoxDriver();
Command invokes the Firefox browser, I hope the reader is familiar with creating the object in java if in case not then follow the link :Java
  • WebDriver - webdriver is the interface which is inherited from SearchContext
  • new - new is the keyword in java which creates an object (address space)in the heap area of CPU
  • FirefoxDriver() - FirefoxDriver() is a constructor of FirefoxDriver class which implements all the methods in the present in the webdriver interface and this opens the Firefox Browser.
  • driver - driver is reference variable , which refers the address space created on the heap.
package Test_Package;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Test_Class {

public static void main(String[] args) {
 WebDriver driver=new FirefoxDriver();
 }

}

  • Open Web page:

We can open the browser by using :
get("url")
a non-static method present in the FirefoxDriver class, it accepts a string as arguments and the string should be the website address.The best thing about the method is it will not give control to the next line till the page loads completely.
package Test_Package;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;


public class Test_Class {

public static void main(String[] args) {
 WebDriver driver=new ChromeDriver();
 driver.get("www.google.com");
 }

}

  • Maximize Browser:

Most of the time when you open firefox browser with selenium, the browser will be in minimized mode but in few scenarios, we might want to maximize the window. we can maximize the browser window with help of:maximize() method present in the window class.
package Test_Package;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;


public class Test_Class {

public static void main(String[] args) {
 WebDriver driver=new ChromeDriver();
 driver.get("www.google.com");
 driver.manage().window().maximize();
 }

}
  •  Browser Size

We can get the size of the browser window by using the getSize() method present in the Dimension class and it returns the Dimension Class type value.
package Test_Package;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;


public class Test_Class {

public static void main(String[] args) {
 WebDriver driver=new ChromeDriver();
 driver.get("www.google.com");
 driver.manage().window().getSize();
 }

}

  •  Get Url

We can get URL of the page the using getCurrentUrl(), it returns Url as a string.
package Test_Package;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;


public class Test_Class {

public static void main(String[] args) {
 WebDriver driver=new ChromeDriver();
 driver.get("www.google.com");
 String current_url= driver.getCurrentUrl();
 System.out.println("Current Url is -->"+current_url);
 }

}

  •  Get Title

We can get URL of the page the using getTitle(), it returns Url as a string.
package Test_Package;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;


public class Test_Class {

public static void main(String[] args) {
 WebDriver driver=new ChromeDriver();
 driver.get("www.google.com");
 String title= driver.getTitle();
 System.out.println("Current Title is -->"+title);
 }

}
  •  Get PageSource:

We can get URL of the page the using getPageSource(), it returns Url as a string.
package Test_Package;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;


public class Test_Class {

public static void main(String[] args) {
 WebDriver driver=new ChromeDriver();
 driver.get("www.google.com");
 String PageSource= driver.getPageSource();
 System.out.println("Current PageSource is -->"+PageSource);
 }

}

CHROME

  • Chrome Developer Tool:

Chrome developer tools allow the user to find CSS, XPath values and also it allows the user to edit the DOM (Document Object Model) on the webpage.Changes done to elements of the DOM will reflect in the page immediately.

Steps to open Developer Tool in Chrome : 

  1. Press F12 key.
  2. Select More Tools > Developer Tools from Chrome's Main Menu.
  3. Right-click a page element and select Inspect.
  4. Press Command+Option+I (Mac) or Control+Shift+I (Windows, Linux).
  5. When we do one of the above-said things, Google opens developer tool like below.
  6. Navigate to elements tab, you can see the HTML source of the page
  7. If you want to inspect any page, you have to click the inspector and choose the element, now it opens the source code.
Chrome Developer Tools 8. Right Click on the Specified Element in the Source Code and Copy XPath as depicted below: Chrome Xpath

FIREFOX:

  • Firebug

1.Install Firebug from Add-ons present in Firefox Browser.Post Installation the icon with bug symbol would be visible. Bug Identification 2. Press F12.3. Click on the Element which you want to locate.4. Xpath for same would be visible on the console as depicted in Picture below: Firefox

Locators:

Locators provide a way to access the HTML elements from a web page. In Selenium, we can use locators to perform actions on the text boxes, links, checkboxes and other web elements.Locators are the basic building blocks of a web page. A web developer must use a proper and consistent locator scheme for a website. Also, a test engineer must choose the correct locator strategy to automate the online workflows.Selenium names eight types of locators to find the elements on a web page.
  1. ID
  2. Name
  3. Link Text
  4. Partial Link Text
  5. Tag Name
  6. CSS Class
  7. CSS Selector
  8. XPath

Description:

  • ID:

It is a unique reference for a web object that the developer sets while writing the code. Ideally, the ID should not repeat on a page, but the browsers do allow exceptions to this rule. The ID is no doubt the best locator to use in Selenium. Still, if it belongs to an HTML table, then it’s possible that it would change or disappear from the list. Hence, you need to put in a more advanced locator technique.
 id="user" class="required" type="text">

WebElement item = driver.findElement(By.id("user"));
Highlights:
It is preferable to have a unique id, so it is unlikely to meet similar values.
Lowlights:
Feasible for elements with fixed IDs but not for the generated ones.
  • Name:

Every form has input fields with unique names. Names are unique most of the times, but it’s not a restriction. However, a field name locator is the best choice for testing a login form. But when you have multiple login types on the same page then you should use locators with a different scheme. Let’s see the example where you can use either the id or the field name.
 id="user" name="admin" class="required" type="text">

WebElement locator = driver.findElement(By.name("admin"));
Highlights:
It is more appropriate to use it when you have a list of similar types of elements.
Lowlights:
Using it with a dynamically generated list is tough.
  • Link Text:

It is a perfect way to find the links on a page.
 href="http://www.google.com">How to use locators?

WebElement item = driver.findElement(By.linkText("How to use locators?"));
Highlights:
  • It’ll only work for anchor tags.
  • Use it for checking navigation flows.
Lowlights:
You need to provide the link text for it to work.
  • Partial Link Text:

It is almost similar to the previous locator. It differs in the way you use it to find the element.
 href="http://www.google.com">How to use locators? WebElement item = driver.findElement(By.PartialLinkText("How to use locators?"));


  • Tag Name:

You can better understand to use this locator from the below example.
List<WebElement> linkElements = driver.findElements(By.tagName("results")); String[] linkTexts = new String[linkElements.size()]
  • CSS:

The CSS class locator uses a specific class attribute to get to the first element on a web page. It is useful for items that own a unique style.
CSS class locator example:
WebElement element =driver.findElement(By.className(“sample”));
  • CSS Selector:
CSS Selectors are no different than the XPaths. But they are resilient and powerful. Unlike the XPath, they aren’t dependent on the DOM structure. They can help you perform actions which are difficult to do with XPath.
CSS Selector example:

WebElement CheckElements = driver.findElements(By.cssSelector("input[id=email']"));
Highlights:
  • Relatively speedier than using the XPath.
  • Its usage is growing as the web pages are getting more style-centric.
  • It’s easy to define a unique CSS locator as you can combine multiple CSS attributes.
Lowlights:
It’s not easy to form a CSS selector and requires a deeper understanding of the CSS/Javascript.
  • XPATH:

XPath is a perfect technique for walking through the DOM structure of the web page. XPath locators are robust and reliable. It is one method which guarantees to locate any element on the page using the XPath expression. But you should be very careful while forming an XPath as it may not work if there are changes in the web application.We can classify XPaths in the following two groups.I- Absolute XPath.It starts from the root element within the web page or part of the page and goes to identify the target element.
Absolute XPath Example:

HTML/head/body/table/tr/td
To use locators like the XPath is easy as you give the direct element path. But the XPath would break when the element structure changes.II- Relative XPath.The relative XPath are easy to manage as they are short and concise. It is also better than the previous XPath style as it may survive the changes in the Page HTML to a certain degree. Though, building a relative XPath is time-consuming and quite difficult as you need to check all the nodes to form the path.
Relative XPath Example:

//table/tr/td
Highlights:
Guarantees to find accurate locators.
Lowlights:
  • It is slow as compared to CSS.
  • It’s browser dependent, and there are differences in IE vs. Firefox XPath implementations.

ChroPath

ChroPath is a developer tool which comes very handy in getting Xpaths and CSS selectors for web elements of a web page.
  • Chropath provides the following benefits:
    • Locator Discovery
    • Save Time
    • Easy Maintenance
  • Locator Discovery- Gives the best, robust locators just in a single click.
  • Save Time- No more hit and trial locators. Get all your relevant XPath and CSS selectors which can be used directly in automation script mode.
  • Easy Maintenance- Verify, edit and modify locators in no time and get the number of matching nodes and scroll matching elements into the view area.

Installation of Chropath

Chropath can be Installed from the following link for the Different Browsers: Chrome:

ForChrome

How to Use Chropath
  • Click on the Plugin by Pressing F12.


Plugin1

  • Inspect Element as shown in Figure below


InspectElement

Click the Element which is to be located

Click on Element

  • Find the Relative and Absolute Xpath and CSS Selector Below, Look it is very simple.


Xpath

Best Books available